Laravel Middleware / Route Groups

11,427

Solution 1

Using Route group is easy for maintenance/modification , other wise you will have to remember each controller where you are using certain middle ware, of course this not a concern in a small medium sized application, but this will be hard in a large application where is lots of controller and references to middle ware.

Solution 2

The suggested options did not work for me but when I checked the laravel documentation, I found this:

Route::middleware(['web'])->group(function () {
    //Your routes here
});

It works for me. Laravel 8.*

Solution 3

You are almost there, just remove the Route::auth():

Route::group(['middleware' => 'auth'], function () {
    Route::get('/home', 'HomeController@index');
    //add more Routes here
});

Solution 4

There is no real difference, personally i use groups for the standard middleware and put exceptions in the construct

Share:
11,427
scottevans93
Author by

scottevans93

Updated on August 21, 2022

Comments

  • scottevans93
    scottevans93 over 1 year

    I'm fairly new to Laravel, so this question may obvious to some.

    In the case of running checks per HTTP request, for example User Authentication. Is there a better, more efficient or simple correct way to run these checks. From my initial research it would seem that this could be accomplished using either MiddleWare, eg.

    public function __construct()
    {
        $this->middleware('auth');
    }
    

    It also seems like it would be possible using routing groups, eg.

    Route::group(['middleware' => 'auth'], function () {
        Route::get('/', function ()    {
            // Uses Auth Middleware
        });
    
        Route::get('user/profile', function () {
            // Uses Auth Middleware
        });
    });
    

    Is there any benefits of doing this either of these two ways? Apart from the obvious benefit of not having to put $this->middleware('auth'); in every controller auth would need to be checked.

    Thanks

    Edit..

    After taking on your advice I attempted to utilities the route grouping to control my Auth MiddleWare. But this has seemed to have broken my site.

    Route::group(['middleware' => 'auth'], function () {
        Route::auth();
    
        Route::get('/home', 'HomeController@index');
    
        Route::get ( '/redirect/{provider}', 'SocialAuthController@redirect' );
        Route::get ( '/callback/{provider}', 'SocialAuthController@callback' );
    });
    

    Am I missing something obvious?

  • Jeffrey Troost
    Jeffrey Troost over 7 years
    a middleware used only once or twice, age gate for a specific page for example
  • Mohamed Raza
    Mohamed Raza over 2 years
    got the source from https://vi.stackfinder.net/questions/38745291/laravel-middle‌​ware-route-groups