Search code examples
laravelrouteslaravel-routinglaravel-middleware

Laravel grouping routes what is best prefix or middleware


When I start thinking grouping my routes and check the documentation. I lost there. There are too many things like prefix, middleware etc.

What is the best way to group routes?

Route::group(['middleware' => 'admin'], function () {});

Route::group(['prefix' => 'admin'], function () {});

Route::group(['namespace' => 'admin'], function () {})

Which approach is best? And why? When to use what approach?


Solution

  • Wait. Prefix and middleware are two different things

    prefix is a way to Prefix your routes and avoid unnecessary typing e.g:

    Route::get('post/all','Controller@post');
    Route::get('post/user','Controller@post');
    

    This can be grouped using prefix post

    Route::group(['prefix' => 'post'], function(){
        Route::get('all','Controller@post');
        Route::get('user','Controller@post');
    })
    

    In the other hand, Middleware :

    Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

    For example using last example now i want the users to be authenticated in my post routes. I can apply a middleware to this group like this:

    Route::group(['prefix' => 'post', 'middleware' => ['auth']], function(){
            Route::get('all','Controller@post');
            Route::get('user','Controller@post');
        })
    

    You should check the docs to get more informed.

    https://laravel.com/docs/5.5/middleware

    https://laravel.com/docs/5.5/routing#route-groups