Multi-User Roles in Laravel 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-&gt;hasMany('App\Role');
}

public function getRoles()
{
    $roles_collection = $this-&gt;roles;
    $roles = [];
    foreach ($roles_collection as $role) {
        $roles[] = $role['role'];
    }
    return $roles;
}

public function referee()
{
    if (in_array('referee', $this-&gt;getRoles())) {
        return true;
    } else {
        return false;
    }
}

public function player()
{
    if (in_array('player', $this-&gt;getRoles())) {
        return true;
    } else {
        return false;
    }
}

public function coach()
{
    if (in_array('coach', $this-&gt;getRoles())) {
        return true;
    } else {
        return false;
    }
}


Example of checking the User role, called from the controller:

if (Auth::user()-&gt;referee()) {
       echo 'referee';
}
I do not have much experience with Laravel, so I will comment on your code as it is presented, but keep in mind that I may miss something which is already handled by the framework.

The first thing which strikes my mind is the getRoles() method. To me it seems you are doing the work of the native function array_column(). This means the method can be reduced to:

public function getRoles() {

    return array_column($this-&gt;roles, 'role');

}


I even think you could extract only the role names into a property. I am not familiar with how Laravel deals with databases, but I am sure you can extract only the role names associated with the user directly from the database. If you then extract the roles during instantiation of the class, you can remove the getRoles() method altogether.



I would also remove the methods player, coach and referee and replace them with a generic method. This is to make it easier in the future if you add/remove new roles. Consider the following method.

public function hasRole($role) {

    return in_array($roles, $this-&gt;getRoles());

}


You would then check if a user by simply writing the role name.

if(Auth::user()-&gt;hasRole('referee')) {
    // Do awesome stuff here
}


This would reduce the number of methods inside your class and make it so you wouldn't have to edit your exiting code just to add a new role. This follows the open-closed principle which states that a class should be open for extension, but closed for modification. 

Now you can also pass the role name as variable (if you ever need to) without the fear of an undefined method error as the method would simply return false.

Happy coding!