Is there a method to override RouteServiceProvider::HOME in Laravel?

Viewed 9633

I have recently started learning Laravel. I am overriding the redirectTo() method in the default LoginController in my Laravel app.

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function redirectTo()
    {
        return '/dashboard';
    }
}

It is working fine but if an already authenticated user tries to login again (the user has not logged out and tries to visit the '/login' route), the user is redirected to '/home' which obviously is the RouteServiceProvider::HOME constant. I can simply change the RouteServiceProvider::HOME constant but there must surely be a better option. Also, if the redirect depends on the role of the user then simply changing the constant won't do any good. So what is the proper way of overriding the RouteServiceProvider::HOME constant?

4 Answers

It's not a method but a constant. You can change it in app\Providers\RouteServiceProviders.php You'll find this line:

public const HOME = '/home';

Change it for whatever you'd like. If you don't want to change it and only change it locally in the

protected $redirectTo = RouteServiceProvider::HOME;

line to

protected $redirectTo = '/whatever'

In Laravel8 you can override following method in LoginController

protected function authenticated(Request $request, $user)
{
    return redirect('/dashboard');
}

and in app\Http\Middleware\RedirectIfAuthenticated.php

public function handle($request, Closure $next, $guard = null)
{
    
    
    if (Auth::guard($guard)->check()) {
        
        return redirect('/dashboard');
        
        //return redirect(RouteServiceProvider::HOME);

    }

    return $next($request);
}

You can also override the redirectTo method if you need a dyamic property.

/**
 * @return string
 */
public function redirectTo() : string
{
    return '/dashboard';
}

In Laravel 8 you can modify App\Http\Controllers\Auth\AuthenticatedSessionController. On the last line of function Store() you can replace the constant ::HOME to a function in the same controller returning a string, like this example bellow.

public function store(LoginRequest $request)
{
    $request->authenticate();

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

    return redirect()->intended(self::home($request));
}

public static function home(LoginRequest $request) : string {

    $user_type = UserType::find($request->user_type_id);
    
    if ($user_type->name == 'Admin') {
        return '/dashboard';
    }

    return '/home';

}

This example is using $request data but you could also use Session instead.

Related