Tuesday, November 15, 2022

[FIXED] How to redirect the user to a specific route after login/register?

Issue

I have multi language application, so when the user logs in or register they need to be redirect to their home of the specific language. In my case en/home or pt/home.

I already tried to overwrite the $redirectTo property in the Login/Register Controllers, but it does not work.

protected $redirectTo = '/home';
protected function redirectTo()
{
    return  app()->getLocale().'/home';
}

Also tried to use theauthenticated method:

protected function authenticated(Request $request, $user)
{
    return redirect(app()->getLocale() .'/home');
}

Why this methods are not working? I looked most of the questions about this here in SO but none of the answers worked so far.


Solution

It was actually a problem on the RedirectIfAuthenticated.php file. I had to change the handle function to:

 public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect()->route('home', app()->getLocale());
    }

    return $next($request);
}

When a user closes the browser without loging out and then try to access the page again in a short period of time (before the login token expires) this is function is called instead of the redirectTo() method in the LoginController. So the problem was only happening in this specific case.



Answered By - Piazzi
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.