I am very new to Laravel. I am building a website where multiple users can have one or more roles. I have a users table and a user_roles
table. Each user_roles
column has a user_id
and an enum field where they can be a "referee", "coach", or "player". Whenever I want to check if the User
is a certain member of a role I call a referee, coach, or player function in my model from the controller. Is my structure and code efficient, or is there any way to clean it up?
User.php
public function roles()
{
return $this->hasMany('App\Role');
}
public function getRoles()
{
$roles_collection = $this->roles;
$roles = [];
foreach ($roles_collection as $role) {
$roles[] = $role['role'];
}
return $roles;
}
public function referee()
{
if (in_array('referee', $this->getRoles())) {
return true;
} else {
return false;
}
}
public function player()
{
if (in_array('player', $this->getRoles())) {
return true;
} else {
return false;
}
}
public function coach()
{
if (in_array('coach', $this->getRoles())) {
return true;
} else {
return false;
}
}
Example of checking the User
role, called from the controller:
if (Auth::user()->referee()) {
echo 'referee';
}