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

maltekiefer's avatar

How to understand pivot?

Hello guys,

I hope you can help me to understand pivot tables. Currently, I am in a situation where I think I need pivot tables.

I have three tables, one called enduser, one hosts and the last one notes.

hosts have 1 FK enduser_id

notes have 1 FK hosts_id

Now I want to get all notes with the enduser id. So in the normal SQL I would go this way:

SELECT * FROM notes WHERE hosts_ID IN (SELECT id FROM hosts WHERE enduser_id = :id)

How can I make this call in a Laravel way? Is this really pivot?

0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You dont need a pivot for this. You can do it with a regular relationship. Lets say your Note model has a relationship called hosts()

$notes = Note::whereHas('hosts', function($query) use ($enduserId) {
    $query->where('enduser_id', $enduserId);
});
1 like
maltekiefer's avatar

OK. I tried it like this:

    public function getNotesByUser($id)
    {
        $notes = Note::whereHas('host', function($query) use ($id) {
            $query->where('enduser_id', $id);
        });

        return response()->json($notes);

    }

The model notehas this:

    public function host()
    {
        return $this->belongsTo('\App\Models\Host', 'host_id', 'id');
    }

But the return is empty. But there are notes for the host for the enduser

maltekiefer's avatar

Oh man, I forget ->get() I am sorry it is working

Please or to participate in this conversation.