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

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.