Set your relationships first
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
then it could be something like this
if (Auth::user()->roles()->pluck('role_name')->contains('admin')) {
//
}
But I recomend to you this package
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
i will explain what i have in the first section and then what i want to get.
I have those 3 tables:
first: users
protected $fillable = [
'name', 'email', 'password',
];
the pivot table: user_to_role
protected $fillable = [
'id', 'user_id', 'role_id'
];
and the third one: roles
protected $fillable = [
'id', 'role_name',
];
role_name is admin and client
When I login/register I want to show the view for the specific role of the user
but I don't really know how to do that in the controller, I have something like this but I know it's not good
public function index()
{
if(Auth::user()->role_id==1){
and something here wich i dont know
return view('homeadmin');
}
}
I know i have to take the role id from the 3th table, make the connection with the pivot and then with the user but i dont really know how
@gzai defining your intermediate table with its own model is a bit unconventional. Its not necessary.
To follow convention, your join table should be called role_user
You can then define the following:
User belongsToMany Role
// User
public function roles()
{
return $this->belongsToMany(Role::class);
}
Role belongsToMany User
// Role
public function user()
{
return $this->belongsToMany(User::class);
}
and then on your User model you can add the following:
public function hasRole(...$roles)
{
foreach($roles as $role)
{
if($this->roles->contains('name', $role))
{
return true;
}
}
return false;
}
which will allow you to check
if(Auth::user()->hasRole('admin')){
// do something
}
You shouldn't use ids for Roles within your system. Stick to the roles name as that won't change.
Please or to participate in this conversation.