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

shiraj's avatar

Querying polymorphic relation using eloquent builder instance such that result is also an eloquent builder's instance.

I am stuck at the fee search filter part in my web app. My setup of polymorphic table is,

Models:

  1. FeeDetail. (columns: id, feeable_id, feeable_type, total_amount, ...)

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

2)Student. (columns: id, name, phone, ...)

public function fees() { return $this->morphMany(FeeDetail::class,'feeable'); }

3)Teacher. (columns: id, name, phone, ...)

public function fees() { return $this->morphMany(FeeDetail::class,'feeable'); }

I am applying a FeeSearch filter which uses Eloquent builder and while adding filter, i can do where() for searching columns of FeeDetail itself and wherehas() for other relation tables but not for polymorphic relation because it doesnot support has()/wherehas().

What i want: If i search with a student/teacher's name, I need to get only those feedetail rows whose polymorphic table's(Student or teacher table's) name matches to the provided search input.

In my PersonName.php filter i have a $builder which is an instance of FeeDetail class. So from here, i need to add a logic to goto student or teacher class to apply filter.

0 likes
0 replies

Please or to participate in this conversation.