How to modify the logout redirect path

Published on April 8th, 2018

If you use Laravel there is a chance that you have taken a deeper look into the login functionality and you might have seen this trait.

trait RedirectsUsers
{
    /**
     * Get the post register / login redirect path.
     *
     * @return string
     */
    public function redirectPath()
    {
        if (method_exists($this, 'redirectTo')) {
            return $this->redirectTo();
        }

        return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
    }
}

This trait is responsible for redirecting the users when they login. As you can see, there are two possibilities to achieve that. On the one side, you could define a redirectTo method and return a route for instance or on the other side, you could define a class property called redirectTo.

If you look for a possibility to redirecting users when they logout, you will not find one. But thanks to traits, we can get this working very quickly.

In the LoginController this trait is pulled in.

use AuthenticatesUsers;

Replace it with

use AuthenticatesUsers {
    logout as doLogout;
}

That means, that the original logout method which comes from the trait is now aliased to doLogoutand we can simply create a new logout method in our LoginControllerand reference to the "old" logout, now doLogout.

Could look like this:

public function logout(Request $request)
{
    $this->doLogout($request);

    return redirect()->route('login');
}

The only thing we have to take care about is, that we have to call the original logout method (which is now called doLogout), that handles all the logical stuff for logging a user really out. You can just redirect to any route you like. That's it!

Bobby Bouwmann and I are writing a book called "Laravel Secrets".
You will learn everything about the undocumented secrets of the popular Laravel framework. You can sign up using the form below to get early updates.
      Visit laravelsecrets.com to get more information.