Organizing route files in Laravel

Organizing route files in Laravel

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

How I solved the issue

In app/Providers/RouteServiceProvider.php , in boot method

/**
 * 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'));
    });

}

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 here.

If you like the tip, I wrote another article about how to secure phpMyAdmin. You can read about it here

要查看或添加评论,请登录

Bijay Das的更多文章

社区洞察

其他会员也浏览了