I might be overlooking this in the docs (Laravel 4.0) but I need to know how to query a many-to-many relationship to see if a particular relationship exists. In the Laravel 4 docs, the example is a user with many roles. Suppose I have a user that is assigned three roles and I have eager-loaded the roles, how can I check to see if one of the roles is "admin" (id: 3). I'm imagining something like...
if ( $user->roles()->find(3) ) {
// $user is admin
}
Doing something like that results in an error where the id column is ambiguous. I just don't want to resort to writing another query that doesn't take advantage of the fact that I have already eager-loaded the relationship. Please note that my actual situation has nothing to do with user roles. I was just using that as an example.
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