Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mimiloca's avatar

How to make query for fetching specific id in eloquent many to many?

I'm trying to access a specific club id and displaying all the members under the same club id. This function is for admin page.

Below is the code that I have tried but it fetching all the user including the non members. How can I fix this query?


    club                member                     club_member 
id |     name   |     |id  |  name |        | id| id_club | id_member|
---|------------|     |----| ------|        |-------------------------
1  | Sc Club    |     | 1  | Maria |        | 1 |    1    |    1     |
2  | Mimes Club |     | 2  | Julia |        | 2 |    1    |    3     |
                      | 3  | Danny |        | 3 |    2    |    1     |
                      | 4  | Olie  |        | 4 |    2    |    2     |
                                            | 5 |    1    |    4     |



I'm trying to access the club id_2 and displaying the user under club id=2 which is Maria and Julia

public function show()
    {
        $clubs = Club::with('members')->get();
        return view('club.member')->with('club', $clubs); 
    }
0 likes
2 replies
MarianoMoreyra's avatar
Level 25

Hi @mimiloca

You are not specifying any club id in your Eloquent query.

If you want to get the club with id 2 you should do:

$clubs = Club::with('members')->where('id', 2)->get();

Although, you should pass the id to your show method:

public function show($id)
{
    $clubs = Club::with('members')->where('id', $id)->get();

    return view('club.member')->with('club', $clubs); 
}

and update your route to pass that variable

Please or to participate in this conversation.