Laravel: Two ways to shrink your Route file
When your routes files become so large, it makes them cumbersome to maintain.
One day, I decided to make a example project with a lot of routes. Quickly my web.php
file started to show cracks. Like almost 1000 lines of declaring routes even with some of the helpers. Until I discovered two simple solutions.
1. Call other files
I think some PHP masters will kill me for what I’m going to do, but it works nonetheless: just call another PHP file.
// routes/web.phpRoute::get('user')
->uses('UserController@user');Route::prefix('podcasts')
->name('podcasts')
->group(__DIR__ . '/podcasts.php');
What I did in the last bolded line of code was simple. I’m calling another PHP file inside the group()
method. Inside that file, we will put the routes under that group, which will behave like they were inside a anonymous function.
You can also use base_path('routes/podcasts.php')
. Since the routes should be cached on production environments, the difference is only on development, since they’re generated on the go.
2. Use your own Route generator
This is less simple, but more of an automated process so you don’t spend time declaring your routes over and over again.
We are gonna make a class called RoutesGenerator
, and we will add methods that will register the routes dynamically. These may have some type of configuration based on the method arguments. We can be just lazy and use the a Real-time Facade to call it inside this file, but in my case I will use just an static function which I consider more straightforward.
<?phpnamespace App\Http;class RoutesGenerator
{
public static function byGenres(array $genres)
{
foreach($genres as $genre) {
Route::get($genre)
->uses('GenresController@get' . ucfirst($genre));
}
}
}
Then, we call the method on the routes file.
// routes/web.phpRoute::get('user')
->uses('UserController@user');$genres = [
'entertainment', 'games', 'music', 'comedy', 'drama'
];Route::prefix('podcasts')
->name('podcasts')
->group(App\Http\RoutesGenerator::byGenres($genres));
That’s pretty much you can do to slim your routes. These also shouldn’t have any problem for caching them as long there is not a Closure in them.