Answer the question
In order to leave comments, you need to log in
How to access the table of roles?
Good evening everyone!
We have a condition that checks the user's role_id
So already we have a user_role table that has user_id and role_id columns, how do we access the user_role table to check if the user has a role there?
@if(Auth::user() && Auth::user()->role_id===1)
Answer the question
In order to leave comments, you need to log in
In the user model
// отношение
public function roles()
{
return $this->belongsToMany('App\Models\Role', 'user_role');
}
// проверка
public function hasRole($id)
{
return $this->roles()
->where('roles.id', $id)
->exists();
}
// для наглядности
public function isAdmin()
{
return $this->hasRole(Role::ID__ADMIN);
}
// 1 это ид роли
const ID__ADMIN = 1;
if ($user->isAdmin()) {
// code...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question