Welcome, I hope my blog is of some use for you!

Laravel

How to set logout redirect path in laravel 5.3+

You can log out of your application, but after logging out who said you wanted to be redirected to the root of your domain? How do we manage to change the logout redirect path in Laravel? I once asked this question myself. So I wrote this article to teach you how.

The method in laravel 5.7+ that is being called when you’re logging out is as follows:

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

$request->session()->invalidate();

return $this->loggedOut($request) ?: redirect('/');
}

Now we can easily overwrite the loggedOut method. This method is exactly there for this reason.
When we view the core method we see it’s empty. So it will return nothing and calls the normal redirect method.

But when we overwrite we can do whatever is needed.

protected function loggedOut(Request $request)
{
return redirect('to-the-page-you-want-to');
}

Laravel 5.7 and before

This was not the case in Laravel 5.7 and before. In laravel 5.7 and before the method being called was as follows:

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

$request->session()->flush();

$request->session()->regenerate();

return redirect('/');
}

You can see there is no real hook where you can change the redirect url, because it’s static.
This means before laravel 5.7 we had to overwrite this method, all to just set a different redirect path. The best method for doing so before laravel 5.7 was by overwriting the use AuthenticateUsers trait with:

use AuthenticatesUsers {
logout as performLogout;
}

After this we could overwrite to logout method like:

public function logout(Request $request)
{
$this->performLogout($request);
return redirect()->route('your_route');
}

Conclusion

Since laravel 5.7 it is significally easier than it was before.
There is finally a logout hook that you can catch on to.

Related posts
Laravel

No more helper functions for Laravel?

Laravel

Translatable resource routes in Laravel

Laravel

Force deleting event in Laravel

Laravel

Save a model with custom attributes - Laravel 5.4+

Sign up for our Newsletter and
stay informed

Leave a Reply

Your email address will not be published. Required fields are marked *