Laravel Auto redirect if not logged in

David Carr

1 min read - 15th Dec, 2016

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

 

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.