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

getupkid's avatar

Is this possible: hasManyThrough through hasManyThrough?

Is it possible?

Consider this hypothetical relationship, for example:

A city has many schools. A school has many teachers. A teacher has many students. A student has many assignments.

With hasManyThrough, I can get all the students from a city

 public function students() {
     return $this->hasManyThrough(Student::class, Teacher::class);
 }

but would it be possible to get all the assignments from a city?

I tried these two with no luck:

 // City model
 public function assignments() {
     return $this->hasManyThrough(Assignment::class, Student::class);
 }

(complains about there not being a foreign key for City on Students)

and:

 // City model
 public function assignments() {
     return $this->hasManyThrough(Assignment::class, $this->students());
 }

(fatal error)

Alternatively, if this type of relationship is not possible in an Eloquent model, how would you go about retrieving all assignments from a city in the best way?

0 likes
1 reply
getupkid's avatar
getupkid
OP
Best Answer
Level 3

For anyone with this issue, this is the solution I came up with:

 $assignments = new Collection();

 foreach ($city->students as $student) {
      foreach ($student->assignments as $assignment) {
           $assignments->add($assignment);
      }
  }

Not sure if there is a cleaner way but I don't think the relationship can be defined properly this way. This at least got me the collection I was looking for.

Please or to participate in this conversation.