-1

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 Answers2

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.

Techno
  • 1,668
  • 1
  • 9
  • 19
-1
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(),
    ]);
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 14 '22 at 06:26