Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 redirect to home page if attempting to go to login screen

I have a login screen which is the base url (www.mysite.com/).

When a user logs in they are redirected to their home page (/home).

But the can still get back to the login page if they go to the root.

How do I make it so logged in users are sent back to their home page if they are logged in (if they are not, of course they see the login page)?

like image 831
imperium2335 Avatar asked Sep 06 '15 14:09

imperium2335


2 Answers

I did this in my router, although I'm not sure if it's the best solution:

Route::get('/', function () {
    if(Auth::check()) {
        return redirect('/dashboard');
    } else {
        return view('auth.login');
    }
});
like image 73
imperium2335 Avatar answered Nov 06 '22 07:11

imperium2335


You should use middleware for this.

Laravel 5 has already a 'guest' middleware out of the box you can use, so just doing the following should be enough:

Route::get('/', ['middleware' =>'guest', function(){
  return view('auth.login');
}]);

Then in the middleware file App\Http\Middleware\RedirectIfAuthenticated you can specify where the user is redirected to.

The default is /home.

like image 7
lordthorzonus Avatar answered Nov 06 '22 09:11

lordthorzonus