Forwarding Laravel 5 to another Role Based Role

I want to redirect my user to another route based on their role. I have two protected areas in my application, β€œadmin” and β€œdashboard”. I would like to check if the user is authenticated and then redirect to the intended one, but if the user has a movie editor, he should be redirected to the dashboard, otherwise, if he has a role, the administrator should be redirected to the administration area.

I use the AuthenticatesAndRegistersUsers class in my login. I have this on my custom controller:

/** * The default redirecTo path. * */ protected $redirectTo = '/dashboard'; 

Therefore, when the user authenticates, he will be redirected to the control panel, but I would like to check if the intended URL is on the route of the administrators group, and if the user has the administrator role, he should be redirected to the administrator area.

I use this middleware to redirect to login:

 public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('auth/login'); } } return $next($request); } 
+6
source share
3 answers

You can overwrite the redirectPath method used by the AuthController in AuthController to enter the logic you need. Something like that:

 /** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { // Logic that determines where to send the user if (\Auth::user()->type == 'admin') { return '/admin'; } return '/dashboard'; } 

EDIT:

Laravel uses the following declaration in the AuthenticatesAndRegistersUsers to redirect the user after a successful login:

 return redirect()->intended($this->redirectPath()); 

This will try to redirect the user to the previously used URL.

If you need to redirect users to the right place when they are already logged in, this would be best done by adding more logic to the authentication middleware.

+6
source

Another approach is to override the authenticated method

 public function authenticated() { if(Auth::check()) { if(\Auth::user()->hasRole('Super Admin')) { return redirect('/admin-dashboard'); } else { return redirect('/user-dashbaord'); } } } 
+1
source

I use this one. You also need to modify the RedirectIfAuthenticated middleware so that it does not go home. Only for different custom panels.

 public function authenticated() { if($request->user()->hasRole('admin')) { // return redirect()->intended(route('admin.index')); return redirect()->route('admin.index'); } if($request->user()->hasRole('super')) { return redirect()->route('super.index'); } if($request->user()->hasRole('officer')) { return redirect()->route('officer.index'); } } 
0
source

Source: https://habr.com/ru/post/989643/


All Articles