Friday 21 October 2016 at 12:08

Laravel Login Authentication and Redirect

By Eric Antoine Scuccimarra

I was having a hard time with the Laravel auth package. If you use the out-of-the-box Laravel Auth, if you try to access a page you don't have access to the Auth will redirect you to the login page and then after a successful login redirect you back to the page you were trying to access.

This works fine. But if I go to a page and then click on login it would redirect me back to a page specified in the Auth controller instead of to the page I was on before I clicked login. I searched for a while and found some info, but not much addressing this specific issue. 

I finally found this thread on Laracasts which gives a simple and easy solution to the problem. 

The solution is to override the login form method in the LoginController.php in the app directory. I added this function:

public function showLoginForm(){
     if(!session()->has('url.intended')){
          session()->put('url.intended', url()->previous());
     }
     return view('auth.login');
}

This pushes the previous page onto the session as url.intended, which is the same thing the middleware does. But this does it in all cases, not just when the middleware catches an auth error. After login the Auth controllers now send you back to url.intended instead of to the default page specified in $redirectTo.

Labels: coding, laravel


Comments

Login or Register to leave a comment..


Archives