I want to redirect to the user's dashboard according to role. I have created a separate table for the user role and a separate table for the user. I don't understand how I can do that.
This is my middleware code
public function handle(Request $request, Closure $next)
{
if(!Auth::check()){
return redirect()->route('login.user')->with('error', 'Please login first');
}
if(Auth::user()->role == 1){
return $next($request);
}
if(Auth::user()->role == 2){
return redirect()->route('user.dashboard');
}
}
This is my user role table
id | user_type |
---|---|
1 | admin |
2 | user |
This is my user table
id | user_name | user_role_id |
---|---|---|
1 | admin | 1 |
2 | user | 2 |
I would be very happy if you could help me.
CodePudding user response:
In the User Model you have to define the role relationship.
Put this to your User Model:
public function role()
{
return $this->belongsTo(Role::class, 'user_role_id');
}
Of course you have to have the Role model, but I guess you already have that
public function handle(Request $request, Closure $next)
{
if(!Auth::check()){
return redirect()->route('login.user')->with('error', 'Please login first');
}
if(Auth::user()->role->user_type == 'admin'){
return $next($request);
}
if(Auth::user()->role->user_type == 'user'){
return redirect()->route('user.dashboard');
}
}
Another solution could be without relationship just like this:
public function handle(Request $request, Closure $next)
{
if(!Auth::check()){
return redirect()->route('login.user')->with('error', 'Please login first');
}
if(Auth::user()->user_role_id == 1){
return $next($request);
}
if(Auth::user()->user_role_id == 2){
return redirect()->route('user.dashboard');
}
}