Jose Jimenez
Jose Jimenez
Software Architect & Developer
> >

Managing Laravel Application Routes

Published in Laravel on Jun 1, 2014

There are various ways to manage routes for your application. The common practice is to simply use app/routes.php. This is fine, however once your application grows, working with your routes.php can become a tedious task.

For that reason anytime I start a new project I tend to break my routes.php into individual files that manage routes for my application.

Create the /routes/ directory

Create the following folder directory app/routes/, this is where we will store all of our future route files.

Creating a route file

For routing I tend to stay away from Closures, and use Controller classes instead. This allows me to stay consistent and I can manage application workflow better.

When you create a new Laravel application app/controllers/HomeController.php is created for you. However the application uses a Closure instead of using the showWelcome() method that is provided inside that file. For this tutorial we will get rid of the Closure and use the controller method instad.

When creating the route file, it should follow the Controller naming convention except you should be using Route instead of Controller in the name.

Create the file app/routes/HomeRoute.php (belongs to app/routes/HomeController.php), and add:

1Route::get('/', 'HomeController@showWelcome');

Moving forward any Controller method in HomeController.php that has a route, should live under HomeRoute.php, this will allow you to easily find routes and keep things consitent.

Update your app/routes.php file.

Assuming you are following the tutorial from a fresh Laravel install. Start by removing the Closure route found in app/routes.php.

Edit app/routes.php and add the following code.

1call_user_func(function () {
2 $routes = [];
3 $dir = opendir(app_path('routes'));
4 while (($currentFile = readdir($dir)) !== false) {
5 if (substr($currentFile, -4) == '.php') {
6 $routes[] = $currentFile;
7 }
8 }
9 closedir($dir);
10
11 natsort($routes);
12 foreach ($routes as $route) {
13 require app_path('routes/' . $route);
14 }
15});

That block of code will look through your app/routes directory and loads each of the files into your application.

The reason we load the files into an array, is so that we can sort them (nsort()), to ensure files are always loaded the same way on any environment.

Additional notes

Routes execute based on the order they were last loaded in. I normally put those special routes in /app/routes.php after the code block listed above.

e.g. a route to display a user: domain.com/janedoe.

Final thoughts

I hope you guys found this tutorial helpful, if anyone has thoughts/suggestions I would love to hear them.