A
A
alexeygavrilovs2020-02-13 18:10:06
Laravel
alexeygavrilovs, 2020-02-13 18:10:06

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

1 answer(s)
J
jazzus, 2020-02-13
@alexeygavrilovs

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);
}

In the Role model
// 1 это ид роли
const ID__ADMIN = 1;

Check like this
if ($user->isAdmin()) {
      // code...
}

But you don't need to check it. Because Auth::check() will have to be checked and permission conditions can change all the time. And throughout the application will need to be rewritten. Therefore it is better to get into politicians and permissions for roles at once.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question