Search code examples
phplaraveleloquent-relationship

I want to select all Users which are not members of a Group with id=6


My tables

  1. users
id name
Cell 1 Cell 2
Cell 3 Cell 4
  1. group
id name
Cell 1 Cell 2
Cell 3 Cell 4
  1. group_users
id user_id group_id
Cell 1 Cell 2 Cell 4
Cell 3 Cell 4 Cell 6
// All users which are members of group
public function users()
{
    return $this->belongsToMany(User::class);
}
// All groups user belong to
public function groups()
{
    return $this->belongsToMany(Group::class);
}

This is what I have tried to do. I think the problem is that I have to make the $users an array of ids that were fetched and I'm unable to do that. Please help

public function show(Group $group)
{
    //Fetching all members of the group
    $users = $group->users()->get()

    return Inertia::render('Clients/Show', [
            'users' => Group::whereNotIn('id', $users)->get()
    ]);
}

Solution

  • public function show(Group $group)
    {
        //Fetching all members of the group
        $exceptId = $group->users()->pluck('users.id');
    
        return Inertia::render('Clients/Show', [
                //Here it will fetch all users except those with ids matching $exceptId array
                'users' => Group::whereNotIn('id', $exceptId)->get(),
        ]);
    }