phplaravelmany-to-many

Check for a specific relation in Laravel Many-To.Many relationship


I have an application with a User model and a Group model as well as a Many-To-Many relationship defined between both models.

I now would like to check if a user is member of a specific group.

I know that this works

$u = User::find(1);
$g = $u->groups->where('name', 'Administrators')->get();

Then I have the group in $g if the user belongs to it. But I am not interested in the group, I just would like to know if the user belongs to it. Of course, I could work with it, but is seems not to be the best solution. Another approach would be the following:

$u = User::find(1);
$g = $u->groups->where('name', 'Administrators')->count();

This seems a little bit more elegant to me. $g == 0 if the user is not a member, $g == 1 if the user is. But my feeling is that Laravel offers a better solution... There are so many shortcuts in Laravel. I'd be surpried if there wasn't another method tailored for this specific need. But which? (There are so many cases, where there is a belongsTo, has, in or similar method, which would be also useful here.)

I already checked the following links in the Laravel documentation, but they do not mention this use case. Is it so special? Or am I just looking in a completely wrong direction?

https://laravel.com/docs/10.x/eloquent-relationships#querying-relationship-existence

and

https://laravel.com/docs/10.x/eloquent-relationships#many-to-many


Solution

  • @Majva's answer is nearly complete, you can do one of the followings:

    return $user->groups()->where('name', 'Administrators')->exists();
    
    // Or
    return $user->groups()->where('name', 'Administrators')->count();
    
    // Or
    return $user->groups->contains('name', 'Administrators');
    

    You might want to check this section of the documentation.