Search code examples
laravelauthenticationlaravel-5.1middleware

Laravel 5.1: using default Auth middleware globally


I'm trying to use the out-of-box Authenticate middleware globally except on auth/login and auth/logout, so that I don't need to add it in every single controller. I added it to the global middleware list in Kernel (as shown below); however, it gets stuck in an infinite auth/login redirect. For any guest, I want the page to be redirected to auth/login and stay there.

class Kernel extends HttpKernel
{
    protected $middleware = [
        ...
        \App\Http\Middleware\Authenticate::class,
    ];
}

It's happening because when it hits auth/login the first time, the global Authenticate kicks in and redirects to auth/login again over and over.

Is it possible to use the default Authenticate middleware globally as I've described? Do I need to create a new middleware for it?

Edit: I've concluded that Thomas' approach is good enough.


Solution

  • You can always use a Route Groups. In your routes.php file...

    // Your login/logout routes
    Route::get('login', 'Auth\AuthController@getLogin');
    Route::post('login', 'Auth\AuthController@postLogin');
    Route::get('logout', 'Auth\AuthController@getLogout');
    
    Route::group(['middleware' => 'auth'], function() {
        // Put all other routes here and the auth middleware will be applied on them all
    });
    

    Edit: Also, you do not need to add the Authenticate middleware to the global middleware stack. Just leave it in the default $routeMiddleware.

    'auth' => \App\Http\Middleware\Authenticate::class,