twitter github codepen dribbble rss

Split Laravel Routes into Multiple Files

If you look at Laravel 5.3, the routes are not defined in one file anymore like in the previous versions instead they are defined in three files under the routes folder. Two files are for URL routes (api.php and web.php), and the other one is for artisan commands (console.php).

So, what’s that means? Well, we can make our own custom files and divide our routes into those files. You know, making things more organize. My routes can go hundred lines pretty quickly, so it would be nice to split them. But, how are we able to do that?

First, we need to take a look at how does Laravel load its route files which is defined in app/Providers/RouteServiceProvider.php. In that file, there are two functions called mapWebRoutes() and mapApiRoutes(). Those functions contain a route group that loads a route file respectively.

protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

protected function mapApiRoutes()
{
    Route::group([
        'middleware' => 'api',
        'namespace' => $this->namespace,
        'prefix' => 'api',
    ], function ($router) {
        require base_path('routes/api.php');
    });
}

With that in mind, you could just add a new file in routes folder and require it in one of those function like this :

protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/admin.php');
        require base_path('routes/web.php');
    });
}

Easy, right? Just keep in mind about the order of the files as it will determine which route is loaded first.

You can also make your own function if you want. Make sure you call it in the map() function.

public function map()
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    //
}