We saw in previous post, how to disable registration in Laravel. Now let's see, if the registration is enabled, then how can we redirect the user to a custom page after registration or login.


Laravel's build-in authentication system provides a $redirectTo property. This property defines where to redirect user after login or registration. And this property can be overriden in LoginController, RegisterController, and ResetPasswordController. Each of the following controllers use RedirectsUsers trait. Let's take a look at 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';
    }
}

And each of this controllers RegisterController, LoginController and ResetPasswordController have this below variable:

protected $redirectTo = '/';
// OR
protected $redirectTo = '/home';

This variable basically defines the location where the user would be redirected after successfully registering or login in the system. So we can easily change it our needs, in the needed controllers. But, as a part of my new project, I had to redirect the users to their respective profile pages. Or the requirement can also be, that redirect users based on roles. In this cases, we can define a method in this controllers named redirectTo():


Like, inside the LoginController, we can add below code to redirect users to profile page:

protected function redirectTo()
{
    return '/@'.auth()->user()->username;
}

Or if we wanted to redirect users based on roles, we can add below code:

protected function redirectTo()
{
    if (auth()->user()->role_id == 1) {
            return '/admin';
    }
    return '/home';
}