Laravel Auto redirect if not logged in

David Carr

Laravel Framework

Some application are login only meaning there is no ‘front page’ so when landing on the home page and the user is not logged in they should be redirected to the login page. If they are logged in then redirect to the dashboard.

Thankfully Laravel makes this really easy, check out this route: 

Route::get('/', function () {
    return redirect()->intended('dashboard');
});

That’s all that’s needed. The redirect intended looks to redirect to dashboard but only if the user is authenticated as other routes are set to use the auth middleware ie:

Route::get('dashboard', [
    'as' => 'dashboard',
    'uses' => 'Dashboard@index',
    'middleware' => 'auth'
]);

Other ways:

if (Auth::guest()) {
 //is a guest so redirect
 return redirect('login');
}

Or

//if not logged in redirect to login page automatically
return Auth()->authenticated();

 

Copyright © 2006 - 2024 DC Blog - All rights reserved.