Laravel - finding groups that do not belong to a user
I am trying to find all groups that do not belong to a specific user. I know how to do this with fluency, but I was wondering how to find these groups using Eloquent.
This is my user model:
public function groups(){
return $this->belongsToMany("Group");
}
and this is the group model:
public function users(){
return $this->belongsToMany("User");
}
if i do this: User::find(1)->groups
i will select all groups owned by this user, but how to change the process, how to find groups that do NOT belong to this user.
+3
source to share
1 answer
I believe it can be done using the following:
$user = User::find(1);
$groups = Group::whereNotIn('id', $user->groups->modelKeys())->get();
So, you can create a method in your user model like this:
public function undefinedGroups()
{
return Group::whereNotIn('id', $this->groups->modelKeys())->get();
}
Then just do:
User::find(1)->undefinedGroups();
Hope this makes sense.
+3
source to share