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

dominiquevilain's avatar

Getting models through polymorphic relationships

I’m building an app where judges can evaluate students during an examination. In my controllers, i would like to be able to retrieve the students involved in an examination as well as the judges. Something like

Examination::find(1)->students

or

Examination::find(1)->judges

In my database, i have 4 tables:

  • examinations describes an examination
  • students describes a student
  • judges describes a judge
  • attendances, containing examination_id to reference an examination, person_id and person_type to define a poly relationship with the persons potentially involved in the examination.

Of course, it’s easy to get access to everything linked to attendances directly. But what i want is an access to students or judges from examinations through attendances.

At this point, i've found a way to get the results i want (almost) with quite a long QB expression :

Examination::find(1)->attendances()->where('person_type','Student')->get()->load('person’)

Of course, i get a bit of extra data since i retrieve the datas concerning an attendance and those of the student associated. I would like to get only the datas related to the student with a simple Eloquent expression.

Do someone here have a clue to guide me in the right direction?

Thanks a lot!

0 likes
1 reply
dominiquevilain's avatar

I forgot to mention ? that i have already created a method students() in my Examination model where i implement the code that works in my example. So in my controllers, i can write

Examination::find(1)->students()

But, of course, i get the attendance loaded with its student…

EDIT: using ->pluck('person')on the resulting collection retrieves only the intended datas :-)

Please or to participate in this conversation.