Retrieving relationships of relationships using Eloquent in Laravel

Ben Thompson picture Ben Thompson · Sep 23, 2013 · Viewed 51.2k times · Source

I have a database with the following tables and relationships:

Advert 1-1 Car m-1 Model m-1 Brand

If I want to retrieve an Advert, I can simply use:

Advert::find(1);

If I want the details of the car, I could use:

Advert::find(1)->with('Car');

However, if I also want the detail of the Model (following the relationship with Car), what would the syntax be, the following doesn't work:

Advert::find(1)->with('Car')->with('Model');

Many thanks

Answer

Björn picture Björn · Sep 23, 2013

It's in the official documentation under "Eager Loading"

Multiple relationships:

$books = Book::with('author', 'publisher')->get();

Nested relationships:

$books = Book::with('author.contacts')->get();

So for you:

Advert::with('Car.Model')->find(1);