Reputation: 345
I am trying to make a Laravel website that uses Laravel's Auth package. I'm using Laravel 5.3.2.
I have created a field in user table called role
.
Now I want to know how to check the users role during the authentication process and then redirect to a required view based on the role. Please help me figure out how this would be possible.
Thank you very much in advance.
Upvotes: 0
Views: 605
Reputation: 1652
When a user logs in, this is done through your LoginController.php
which is located at app\Http\Controllers\Auth
This controller uses a trait called AuthenticatesUsers
.
This trait has a method called authenticated()
which by default is empty. This method is called if it's not empty by the trait - after all the necessary loggin in stuff has been done.
You could override this method in your AuthenticationController.php
and add the functionality you are asking for. An example would be:
// You actually get an Auth\User object passed to you by the trait!
public function authenticated(Request $request, $user)
{
if($user->role == 'admin') {
// You could do anything here
return redirect()->route('admin-dashboard');
} else {
return redirect()->route('home');
}
}
Upvotes: 4
Reputation: 2354
Beside solution overriding some default Laravel method. I suggest an other approach: redirect user to a route which is responsible for redirect user base on user's role
In AuthController
protected $redirectTo = '/redirect';
In routes
Route::get('redirect', function(){
switch(auth()->user()->role){
case 1:
return redirect()->to();
break;
case 2:
return redirect()->to();
break;
}
})
Upvotes: 1