Do you have multiple routes that make your “routes/web.php” or “routes/api.php” 200-220 lines long?

This article will cover tips on organizing your multiple routes in Laravel. Also, the documentation is an excellent source that helps you learn how to use routing in your Laravel applications.

WHAT IS A ROUTE IN LARAVEL?

A route is a way of creating a request URL for your application. You are free to define a route in whatever manner you like. The Router in laravel framework is one of the classes that is designed to operate at the HTTP level. Basically, routes are readable and SEO friendly. All requests are mapped with the help of routes, and routes are created inside the routes folder.

HANDLING COMPLEX ROUTES

Other than the default structure of routes in Laravel, we can create our own custom route structure. The first thing to do is to create a new service provider by running this artisan command in your terminal

php artisan make:provider CustomRouteServiceProvider

Then replace the default imports with this code

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

You can find your new service provider in “app/Providers” directory. After that, create class properties for namespace and for the custom web and API route directories.

<?php

protected $namespace = 'App\Http\Controllers';
private $webPath = 'routes/custom_web_routes';
private $apiPath = 'routes/custom_api_routes';

You have to create directories inside the “routes” folder for the web and API. These are the following…
1. custom_web_routes
2. custom_api_routes

In “CustomRouteServiceProvider.php” file, create a method called “mapCustomWebRoutes()”. This method will define the custom web routes for the application. These routes are assigned the web middleware group and can also receive session state and CSRF protection just like the default web route.

<?php

public function mapCustomWebRoutes() 
{
    $directory = base_path($this->webPath);
    $files = array_diff(scandir($directory), array('..', '.'));
    foreach ($files as $file) {
        $this->myRoute('web', $this->webPath, $file);
    }
}

The above method will read all the files inside “custom_web_routes” directory and this will make them as a web route automatically.

Aside from that, create also a method for the custom API routes that will look like this,

<?php

public function mapCustomApiRoutes() 
{
    $apiDirectory = base_path($this->apiPath);
    $files = array_diff(scandir($apiDirectory), array('..', '.'));
    foreach ($files as $file) {
        $this->myRoute('api', $this->apiPath, $file, 'api');
    }
}

This method is the same as “mapCustomWebRoutes()” method, but this will work for the API routes inside “custom_api_routes” directory. These routes are typically stateless and are assigned the api middleware group.

The methods mentioned above will not work just yet. In order to make these methods run, we have to implement another method called “myRoute()”.

<?php

public function myRoute($middleware, $group, $file, $prefix = null) 
{ 
    Route::prefix($prefix) ->middleware($middleware)
         ->namespace($this->namespace)
         ->group(base_path($group) . '/' . $file);
}

After we created the methods above, we have to define the custom routes for the application using the “map()” method from parent class “ServiceProvider”.

<?php 

public function map() 
{ 
    $this->mapCustomWebRoutes();
    $this->mapCustomApiRoutes();
}

The last step to work on this class is to bootstrap any application services and load all the routes, by adding parent::boot() on the “boot()” method.

<?php 

public function map() 
{ 
    $this->mapCustomWebRoutes();
    $this->mapCustomApiRoutes();
}

Now, your “CustomRouteServiceProvider.php” class will look like this

<?php 

namespace App\Providers; 
use Illuminate\Support\Facades\Route; 
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; 

class CustomRouteServiceProvider extends ServiceProvider 
{ 
      /** 
      * This namespace is applied to your controller routes. 
      * In addition, it is set as the URL generator's root namespace. 
      * @var string 
      */ 
      protected $namespace = 'App\Http\Controllers'; 
      private $webPath = 'routes/custom_web_routes'; 
      private $apiPath = 'routes/custom_api_routes'; 

      /** 
      * Bootstrap services. 
      * * @return void 
      */ 
      public function boot() 
      { 
            parent::boot(); 
      } 

      /** 
      * Define the routes for the application. 
      * * @return void 
      */ 
      public function map() 
      { 
            $this->mapCustomWebRoutes();
            $this->mapCustomApiRoutes();
      }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    public function mapCustomWebRoutes()
    {
        $directory = base_path($this->webPath);
        $files = array_diff(scandir($directory), array('..', '.'));
        foreach ($files as $file) {
            $this->myRoute('web', $this->webPath, $file);
        }
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    public function mapCustomApiRoutes()
    {
        $apiDirectory = base_path($this->apiPath);
        $files = array_diff(scandir($apiDirectory), array('..', '.'));
        foreach ($files as $file) {
            $this->myRoute('api', $this->apiPath, $file, 'api');
        }
    }

    /**
     * @param      $middleware
     * @param      $group
     * @param      $file
     * @param null $prefix
     */
    public function myRoute($middleware, $group, $file, $prefix = null)
    {
        Route::prefix($prefix)
            ->middleware($middleware)
            ->namespace($this->namespace)
            ->group(base_path($group) . '/' . $file);
    }
}

Register your new ServiceProvider to the “providers[]” array and below in existing “App\Providers\RouteServiceProvider::class” in “config/app.php“.

<?php 

'providers' => [
    ..
    ..
    \App\Providers\CustomRouteServiceProvider::class,
],

ROUTE TESTING

  • In “routes/custom_web_routes ” directory, add a file and named it as “hi.php” and put this code,
<?php

Route::get('/hi', function () {
    return 'web hi';
});

And add another file “hello”.php with this code

<?php

Route::get('/hello', function () {
    return 'web hello';
});

Go to your browser and access these links for example

https://<your_project_domain>/hi
https://<your_project_domain>/hello

And you may see this in your pages, respectively

web hi
https:///hi

web hello
https:///hello

  • In “routes/custom_api_routes” directory, add a file and named it as “hi.php” and put this code,
<?php

Route::get('/hi', function () {
    return 'api hi';
});

And add another file “hello.php” with this

<?php

Route::get('/hello', function () {
    return 'api hello';
});

Go to your browser and access these links for example

https://<your_project_domain>/api/hi
https://<your_project_domain>/api/hello

And you may see this in your pages, respectively

api hi
https:///api/hi

api hello
https:///api/hello

CONCLUSION

Laravel has a very powerful router and is customizable in many ways. To learn more about routing, you could also refer to the official Laravel routing documentation.

Author

Lead Developer at Muggtech | Laravel Expert | VueJS and WordPress Core PHP Developer

Write A Comment