Skip to content

Multiple Route files in Laravel 5

Last updated on February 17, 2018

For small-scale applications single route file is sufficient but large-scale applications its cumbersome to maintain and organize the routes.

The solution for this was creating multiple route files. For example, if you are developing web application and APIs in the same application than its elegant to create separate route files for each. Even you can create separate route files by module or feature.

Laravel 5 supports creating separate route files out of the box and multiple routes file can be registered in RouteServiceProvider. In laravel 4 and below versions we include route files manually in the main route file.

Multiple Route files in Laravel 5

Let me show you what I did. First I created a directory called Routes and moved the standard routes.php file to there and changed that name to web.routes.php and then I created an extra file called api.routes.php

Next, I changed the RouteServiceProvider map method to contain the right calls to both route files and I have created the separate namespace for web and APIs.

group(['namespace' => $this->webNamespace], function ($router) {
            require app_path('Http/Routes/web.routes.php');
        });

        /*
        |--------------------------------------------------------------------------
        | Api Router 
        |--------------------------------------------------------------------------
        */

        $router->group(['namespace' => $this->apiNamespace], function ($router) {
            require app_path('Http/Routes/api.routes.php');
        });

    }
}

NOTE: I have placed all of my web controllers under Web directory and api controller under Api directory. Following two lines indicate that, feel free to change this values as you wish.

protected $webNamespace = 'App\Http\Controllers\Web';
 protected $apiNamespace = 'App\Http\Controllers\Api';

That is it. In this tutorial we have created only two route files, in reality, you can add as many routes as you want, just follow the same logic. I hope this tutorial will help you to organize your routes and project effectively.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments