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.

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

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.

 

  • Jared Speck

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