Because the relationship will be returned as a collection you can use some handy array utilities on the collection items to check if the user has a given role. You might like to make a hasRole
method on the User
model, it would make things look nicer.
public function hasRole($id)
{
return ! $this->roles->filter(function($role) use ($id)
{
return $role->id == $id;
})->isEmpty();
}
And then...
if ($user->hasRole(3))
{
// User is an admin.
}
The hasRole
method uses filter
to remove any roles that don't have the ID that is given to the method. Then you can use isEmpty
on the newly returned collection to see if there were any roles. If it isn't empty then the user has that role.
Of course role management can be made easier by implementing some form of ACL, like Authority: https://github.com/machuga/authority-l4
There's a couple of different packages out there that make dealing with roles and permissions a breeze.
Thanks, that should do it. That is what I was envisioning but I figured I was overlooking something that was built-in. Thanks for the tips on user roles as well, but like I said, I was just using that as an example because it is used in the docs.
what about
$roles = User::find(1)->roles;
if ($roles->contains(2))
{
//
}
source: http://laravel.com/docs/eloquent#collections
although in all honesty I like Jason's answer better
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community