skip to Main Content

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()
    ]);
}

2

Answers


  1. Chosen as BEST ANSWER
    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(),
        ]);
    }
    

  2. If you want to select users who don’t have a relation, you can use whereDoesntHave:

    $users = User
        ::whereDoesntHave('groups', fn($query) => $query->where('id', 1))
        ->get();
    

    In this case I’m querying for all users who dont have a group with id 1 linked.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search