11 months ago

Eager Loading Nested Relationships

Posted 11 months ago by nickdavies07

I'm trying to cut down the queries on my page by making use of Eloquent's nested eager loading relationships.

  • I have Schools, with many assets and that asset has a finance record.
  • I have Schools, with many categories and that category has a type.

I have tried nested eager loading for these relationships by doing this:

$school = School::with('', 'categories.types')->find($id);

Then in the blade view, I've got something like this.

@foreach($school->assets as $asset)
    <td>{{ $school->assets->first()->asset_tag }}</td>
    <td>{{ $school->categories->first()->name }}</td>

Obviously this doesn't work for getting the categories or the types since I'm using the $school->assets in the foreach.

How would I go about getting the data from the categories relationship?

Please sign in or create an account to participate in this conversation.