Laravel Framework

David Carr

Laravel Auto redirect if not logged in

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();

 

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2020 DC Blog. All code MIT license. All rights reserved.