
A few days ago I was building an application in Laravel where I faced the problem of having too many routes in my routes/api.php
and routes/web.php
as my application was expanding these files became larger and larger.
Laravel provides a very flexible way to customize every aspect of our project. So for the routes Laravel provides an option to organize the routes files in RouteServiceProvider
Complete documentation for RouteServiceProvider
is available here
/**
*
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$api_route_options = [
'middleware' => 'api',
'prefix' => 'api',
'namespace' => $this->namespace
];
Route::group($api_route_options, function () {
Route::prefix('web1')->group(base_path('routes/web1.php'));
Route::prefix('web2')->group(base_path('routes/web2.php'));
});
$web_route_options = [
'middleware' => 'web',
'namespace' => $this->namespace
];
Route::group($web_route_options, function () {
Route::prefix('web1')->group(base_path('routes/web1.php'));
Route::prefix('web2')->group(base_path('routes/web2.php'));
});
}
How I solved the issue
In app/Providers/RouteServiceProvider.php
, in boot method
I created separate route files and mapped them.
Route
is a facade that allows us to group routes add middlewares and finally return a closure to map the routes.
Here instead of adding the routes to the controller, I am pointing to add the route file which needs to be added to the configuration.
To know more about Laravel routes you can always refer the official documentation.
If you like the tip, I wrote another article about how to secure phpMyAdmin. You can read about it here