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

Mrtvac's avatar

Eloquent API resources - nested relationship?

Hi,

Well, in resource (School) I've tried to load nested relationship something like this: 'students' => UserResource::collection($this->whenLoaded('classes.user')) but without success.

In controller I have something like this:

SchoolResource::collection(School::with(['classes.user'])->get());

School has many classes. Class can have many students. One student can be only in one class. I wish to return all students that are in particular school.

Is this possible using Eloquent API resource or do I need to make custom response?

0 likes
7 replies
ralphmorris's avatar

You could add the id of the School to your students table? Then create another relationship.

Mrtvac's avatar

That won't work for this case as one student can be in one class in one school. But can also be another class in another school which means that student can be in multiple schools so adding school_id won't work.

But thank you for your suggestion.

I was just wondering will whenLoaded method work with nested relationship. As I could see from the code of whenLoaded function, it only accept one relationship as string.

Mrtvac's avatar

Hi @integrasolid This project was long time ago and I don't work on it anymore so I'm not sure to be honest, but as I could remember, I've used different approach/logic to solve this problem. As I could remember, this nested relationship in resource didn't work at that point.

integrasolid's avatar

@Mrtvac thanks, looks like for now I will settle with not checking whenLoaded for nested relationship

vitsw's avatar

Yes, it's seems that whenLoaded method doesn't check nested relationships. I solved that in this way

...
'parentRelation' => $this->whenLoaded('parentRelation', function () {
     return [
          'id'    => $this->parentRelation->id,
          'title' => $this->when(
		$this->parentRelation->relationLoaded('childRelation'), 
		fn () => $this->parentRelation>childRelation->title
	   )
       ];
 }),
...

Please or to participate in this conversation.