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

Adgower's avatar
Level 14

Query Polymorphic Relationship

I have a students page with where each student has an invoice for the course, and i want to check the status of each invoice (paid/unpaid) for each student.

$event->invoices->where('paid', false)->where('billable_id', $student->id)

That retrieves it fine, but this is a polymorphic relationship so sometimes the billable_id might reference another model. How can I search through only users.

Point me in the right direction! Thanks

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

Please show the relationship definitions

But something like this I would assume

$event->invoices->where('paid', false)->where('billable_id', $student->id)
->where('invoicable_type', 'App\User')->get();
Adgower's avatar
Level 14

@sinnbeck User Model

public function invoices()
    {
        return $this->morphMany('App\Models\Invoice', 'billable');
    }

Invoice Model

public function billable()
    {
        return $this->morphTo();
    }

Please or to participate in this conversation.