Laravel: How to avoid redirecting to home after login?

If you are working on a Laravel 5.1 based project and using Auth class for authentication purpose, chances are you would have faced issue of redirecting to home after login.

While docs say that you can override the behaviour by setting the $redirectedPath value. Thing is it will still not work. After wasting a reasonable time, I figured out the issue.

By default Auth constructor is defined as:

 

public function __construct()
    {        
        $this->middleware('guest', ['except' => 'getLogout']);
    }

This middleware actually calls  RedirectIfAuthenticated trait. If you go to definition you will find:

 

public function handle($request, Closure $next)
    {
        if ($this->auth->check()) {
            return redirect('/home');
        }

        return $next($request);
    }

Hardcoded right. So the best is to omit out the following line from constructor:

$this->middleware('guest', ['except' => 'getLogout']);

Add following protected method to override default redirection:

protected function authenticated(Request $request, User $user)
    {
        return redirect()->intended();
    }

 

And it should work then.

2 Comments