Home > Software engineering >  Get users by meeting id of a pivot table with laravel
Get users by meeting id of a pivot table with laravel

Time:12-28

I have searched for related information but after trying I have not been able to get the results.

I have two many-to-many related tables, I need to list the users that are signed up for the same meeting (meeting_id).

This is the user model:

    public function meetings()
    {
        return $this->belongsToMany(Meeting::class);
    }

And this is the meeting model:

    {
        return $this->belongsToMany(User::class);
    }

I have a pivot table: meeting_user, for example:

ID meeting_id user_Id
1 1 1
2 1 2
3 2 3
4 1 4
5 2 4

I need to get a list: user_id 1, 2 and 4, because they are on meeting_id=1.

I have tried different ways but I can't get the list of users.

This is my controller:

    public function getUsersByMeeting(User $user, Meeting $meeting)
    {
        // $users = Meeting::find($meeting->id)->users->get();

        $users = $user->meetings()->where('meeting_id', $meeting->id)->get();

        return response()->json($users, 200);
    }

I don't know if the method needs the "User $user" parameter (Meeting $meeting yes, to get the $meeting->id).

Thanks !!

CodePudding user response:

You already have Meeting $meeting available in your method. From that variable, you can either access the relationship directly with ->users or a query builder with ->users() if you need additional filtering.

If you don't need any additional filtering, you could just do

public function getUsersByMeeting(User $user, Meeting $meeting)
{
    return response()->json($meeting->users, 200);
}

Note that this will include information about the pivot table.

Here are some of the options you can choose from.

$users = $meeting->users;
$users = $meeting->users()->get();
$users = User::whereHas('meetings', fn ($q) => $q->where('meetings.id', $meeting->id))->get();
  • Related