Search code examples
phplaravellaravel-5.8laravel-authentication

Login view shows blank page with url: /login when logged in


I'm using Laravel build-in authentication methods.

I have a redirect function which returns routes for different user roles.

It doesn't redirect to the specified URL when going to /login it just shows a blank URL with the plain route (/login) in the HTML

I have searched this docs but couldn't find a solution for this problem.

This code does produce the problem I think:

//Auth/LoginController 

protected function redirectTo()
{

    if (!Auth::guest()) {
        if (Auth::user()->is_active != 0) {
            if(Auth::user()->hasRole('administrator')) {
                $this->redirectTo = '/admin';
                return $this->redirectTo;
           } else if(Auth::user()->hasRole('customer')) {
                $this->redirectTo = '/customer';
                return $this->redirectTo;
           } else {
              return '/logout'; 
           } 
        } else {
            return '/dashboard';
        }
    } else {
        return '/login';
    }
}

When i use redirect:

 protected function redirectTo()
    {
        if (!Auth::guest()) {
            if (Auth::user()->is_active != 0) {
                if(Auth::user()->hasRole('administrator')) {
                    $this->redirectTo = '/admin';
                    return redirect($this->redirectTo);
               } else if(Auth::user()->hasRole('customer')) {
                    $this->redirectTo = '/customer';
                    return redirect($this->redirectTo);
               } else {
                  return redirect('/logout'); 
               } 
            } else {
                return redirect('/dashboard');
            }
        } else {
            return redirect('/login');
        }
    }

I get this error:

This page isn’t working [..] redirected you too many times.

How do I redirect users also when going to the login route.

Thanks in advance!!


Solution

  • This solved redirect and too many redirects error because of conflict with another login redirect function:

    protected function loggedOut(Request $request) {
        return redirect('/login');
    }
    
        protected function redirectTo()
    {
        if (!Auth::guest()) {
            if (Auth::user()->is_active != 0) {
                if(Auth::user()->hasRole('administrator')) {
                    $this->redirectTo = '/admin';
                    return redirect($this->redirectTo);
               } else if(Auth::user()->hasRole('customer')) {
                    $this->redirectTo = '/customer';
                    return redirect($this->redirectTo);
               } else {
                  return redirect('/logout'); 
               } 
            } else {
                return redirect('/dashboard');
            }
        } else {
            return view('auth.login');
        }
    }