Skip to content
Advertisement

Laravel Middleware / Route Groups

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement