Laravel Auth Redirection
Published on by Eric L. Barnes
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.
public function redirectPath(){ if (method_exists($this, 'redirectTo')) { return $this->redirectTo(); } return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';}
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:
public function redirectTo(){ return '/@'.auth()->user()->username;}
Eric is the creator of Laravel News and has been covering Laravel since 2012.