Split Laravel Routes into Multiple Files

20 January 2017

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

protectedfunctionmapWebRoutes()

{

Route::group([

'middleware'=>'web',

'namespace'=>$this->namespace,

],function($router){

requirebase_path('routes/web.php');

});

}

protectedfunctionmapApiRoutes()

{

Route::group([

'middleware'=>'api',

'namespace'=>$this->namespace,

'prefix'=>'api',

],function($router){

requirebase_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 :

1

2

3

4

5

6

7

8

9

10

protectedfunctionmapWebRoutes()

{

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.

1

2

3

4

5

6

7

8

publicfunctionmap()

{

$this->mapApiRoutes();

$this->mapWebRoutes();

//

}

Jared Speck

This was exactly what I needed. My web.php file was almost to 1000 lines. Thank you for your post.