0
votes

i've problem, I'm trying to redirect users when they log in by role to their dashboard using middleware in laravel 6. But I'm stucked can't figure out where is the problem in this condition. Please help, thanks kindly.

Each role has this route web.php

Route::group([ 'as'=>'user.', 'prefix'=>'user', 'namespace'=>'User', 'middleware'=>['auth','user']],
    function(){
        Route::get('dashboard', 'DashboardController@index')->name('dashboard');
});

Middleware looks like

public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->role->id == 3 ) {
            return $next($request);
        }else{
            return redirect()->route('login');
        }
    }

RedirectIfAuthenticated

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check() && Auth::user()->role->id == 1 ) {
            return redirect()->route('admin.dashboard');
        }elseif (Auth::guard($guard)->check() && Auth::user()->role->id == 2) {
            return redirect()->route('author.dashboard');
        }elseif (Auth::guard($guard)->check() && Auth::user()->role->id == 3) {
            return redirect()->route('user.dashboard');
        }else{
            
              return $next($request);
        }

And LoginController

 public function __construct()
    {
        if (Auth::check() && Auth::user()->role->id == 1  ) {
            $this->redirectTo = route('admin.dashboard');
        }elseif (Auth::check() && Auth::user()->role->id == 2  ) {
            $this->redirectTo = route('author.dashboard');
        }elseif (Auth::check() && Auth::user()->role->id == 3  ) {
            $this->redirectTo = route('user.dashboard');
        } else {
            $this->middleware('guest')->except('logout');
        }


        
    }
1
doing that in your constructor won't do anything ... the session has not started yet so Auth::check will always return false ... the guest middleware is the place for thatlagbox
Can you help me to fix it please?denyw

1 Answers

0
votes

Your first middleware check if the user is logged AND if he has the role 3.

Maybe change it for :

public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            return $next($request);
        }else{
            return redirect()->route('login');
        }
    }