Laravel 5.3 Login redirects to different pages for multiple users

I have Laravel 5.3 with three different types of users. I want them to be redirected to different pages of the control panel after logging in. For instance:

user -> login -> user-dashboard

admin -> login -> admin-dashboard

I created a middleware called CheckRole :

 public function handle($request, Closure $next) { if($request->user() === null) { return response("Insufficient Permissions" , 401); } $actions = $request->route()->getAction(); $roles = isset($actions['roles']) ? $actions['roles'] : null; if($request->user()->hasAnyRole($roles) || !$roles) { return $next($request); } return response("Insufficient Permissions" , 401); } 

Routes

 Route::group(['middleware' => ['auth','roles'], 'roles' => 'Admin'], function () { // Routes here } 

Roles work just fine.

Now redirectTo= ''; in LoginContoller points to only one view. I checked the documentation, and I believe this has something to do with the guards who have no explanation as to how to set it up.

I also saw multiauth, but I donโ€™t think it would be wise to create different tables for different users and therefore look for an alternative answer.

Any suggestion would be appreciated.

My tables:

 Table users id | name | email --------- 1 | John | john@blah.com 2 | Michael | michael@blah.com Table roles id | name --------- 1 | Admin 2 | PrivilegedMember 3 | Subscriber Table user_role id | user_id | role_id ---------------------- 1 | 1 | 1 2 | 2 | 2 

This may be a duplicate of the following question, but the answer provided leaves it without an explanation of several redirects.

Multiple Authentications in Laravel 5.3

+6
source share
3 answers

LoginController authenticated() method in your LoginController and add the redirect logic there:

 <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { use AuthenticatesUsers; // ... /** * The user has been authenticated. * * @param \Illuminate\Http\Request $request * @param mixed $user * * @return mixed */ protected function authenticated(Request $request, $user) { if($user->hasRole('Admin')) { return redirect()->intended('admin'); } if ($user->hasRole('PrivilegedMember')) { return redirect()->intended('PriviligedMember/index'); } } // ... } 

The method is called after user authentication. See the last two lines of sendLoginResponse :

 /** * Send the response after the user was authenticated. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); return $this->authenticated($request, $this->guard()->user()) ?: redirect()->intended($this->redirectPath()); } 

So this is the perfect candidate for such logic.

One more note to your own answer: AuthenticatesUser is a feature that extends LoginController horizontally, you can safely override any of its methods in your controller without touching the main files.

+6
source

The best way I've found is to use Traits . What we will do is basically the same, but less complex and structured:

1. Instead of creating two tables, our user model will have a role field, in my case I will have: "admin", "employee" and "user".

2. We are going to create a folder with traits, in which case it will be placed in App/Http .

3. We are going to create a new file and call it RedirectTrait.php inside this folder with this content:

 <?php namespace App\Http\Traits; // Or the place where the trait is stored (step 2) use Illuminate\Http\Request; trait RedirectTrait { /** * Where to redirect users after register/login/reset based in roles. * * @param \Iluminate\Http\Request $request * @param mixed $user * @return mixed */ public function RedirectBasedInRole(Request $request, $user) { $route = ''; switch ($user->role) { # Admin case 'admin': $route = '/admin/dashboard/route'; // the admin route break; # Employee case 'employee': $route = '/employee/dashboard/route'; // the employee route break; # User case 'user': $route = '/user/dashboard/route'; // the user route break; default: break; } return redirect()->intended($route); } } 

As you can see, we can โ€œplayโ€ with redirects, but the intended one is necessary. According to laravel documentation:

The designated redirect method redirects the user to the URL they were trying to access before being intercepted by the middleware authentication. A fault-tolerant URI can be provided to this method if the intended destination is not available.

4. Finally, we place the attribute and name it:

  • In the file App/Http/Controllers/Auth/LoginController.php
  use Illuminate\Http\Request; // Add use App\Http\Traits\RedirectTrait; // Call the trait class LoginController extends Controller { ... use RedirectTrait; // Use the trait /** * The user has been authenticated. * * @param \Illuminate\Http\Request $request * @param mixed $user * @return mixed */ protected function authenticated(Request $request, $user) { return $this->RedirectBasedInRole($request, $user); } ... } 

We are rewriting the 'authenticated' method placed in Illuminate\Foundation\Auth\AuthenticatesUsers (which is empty, by the way)

  • We will do the same in the file App/Http/Controllers/Auth/RegisterController.php , but the method will have a different name:
 /** * The user has been registered. * * @param \Illuminate\Http\Request $request * @param mixed $user * @return mixed */ protected function registered(Request $request, $user) { return $this->RedirectBasedInRole($request, $user); } 

We are rewriting the redirection method stored in Illuminate\Foundation\Auth\RegistersUsers and is also empty.

5. Enjoy: D

PS. Password forwarding reset is another story.

+2
source

It seems that the solution below overcomes the process and does the job. But I donโ€™t think this is the right way, since we play with Core files. Some body, please shed light on this.

Go to AuthenticatesUser.php trait.

find SendLoginResponse (request $ request)

Before returning the default path, add your conditions. I changed it below

 protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); if(Auth::User()->hasRole('Admin')) { return redirect()->intended('admin'); } elseif (Auth::User()->hasRole('PrivilegedMember')) { return redirect()->intended('PriviligedMember/index'); } return $this->authenticated($request, $this->guard()->user()) ?: redirect()->intended($this->redirectPath()); } 
0
source

All Articles