Laravel Auth Redirection

Tutorials

January 9th, 2017

laravel-redirectTo.png

When you use Laravel’s built-in Auth system, it provides a redirectTo property on the LoginController, RegisterController, and ResetPasswordController. This property allows you to define the location you want your users sent to after they complete the action.

Inside of Laravel this is setup and implemented through a RedirectsUsers trait and a minor improvement has been added to this that will now allow you to define a redirectTo method with a fallback to the property.

1public function redirectPath()
2{
3 if (method_exists($this, 'redirectTo')) {
4 return $this->redirectTo();
5 }
6
7 return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
8}

With this new method, you now have easier access to perform other actions or to set the location dynamically. As an example, let’s pretend when a user logs in you want to redirect them to their public account page. Inside your LoginController you can now do something like this:

1public function redirectTo()
2{
3 return '/@'.auth()->user()->username;
4}

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.