Laravel Eloquent: eager loading of multiple nested relationships

50,207

Solution 1

You can do

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

Solution 2

Laravel documentation on eager loading recommends listing the relationships in an array as follows:

$books = App\Book::with(['author.contacts', 'author.publishers'])->get();

You can have as many relationships as desired. You can also specify which columns should be included for a relationship like this:

//only id, name and email will be returned for author
//id must always be included
$books = App\Book::with(['author: id, name, email', 'author.contacts', 'author.publishers'])->get();

You may also add constrains as follows:

$books = App\Book::with(['author: id, name, email', 'author.contacts' => function ($query) {
                                          $query->where('address', 'like', '%city%');
                                     }, 'author.publishers'])->get();

Solution 3

So, now you can try

$books = App\Book::with(['author' => function($author){
     $author->with(['contacts', 'publishers'])->get();
}])->get();
Share:
50,207
DrivingInsanee
Author by

DrivingInsanee

Updated on July 05, 2022

Comments

  • DrivingInsanee
    DrivingInsanee almost 2 years

    What laravel says:

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

    What I need is something like this

    $books = App\Book::with('author[contacts,publishers]')->get();
    

    where we eager load multiple relationships within a relationship.

    Is this possible?

  • Chaudhry Waqas
    Chaudhry Waqas about 7 years
    just to add, it will fetch the corresponding author data as well ofcourse.
  • Todd
    Todd almost 7 years
    Follow-up: I have a much more complex model and want to return a single collection, but like the original poster, wish I could use multiple nested relationships at a lower child level like $event = event::with(['streams.experiences.selectors.['digitalprops.f‌​rames','filters']','‌​streams.datacaptures‌​'])->find($eventcode‌​);
  • tisuchi
    tisuchi almost 6 years
    @Todd How do you execute this code in Laravel? $event = event::with(['streams.experiences.selectors.['digitalprops.f‌​rames','filters']','‌​streams.datacaptures‌​'])->find($eventcode‌​);. It shouldn't work...!
  • Todd
    Todd almost 6 years
    Right @tisuchi -- I said I WISH I could... sorry for the confusion.
  • Adam
    Adam almost 5 years
    This is the best overview how to eager load efficiently!
  • msbomrel
    msbomrel over 4 years
    does author is table name or what?
  • Elisha Senoo
    Elisha Senoo over 4 years
    @msbomrel, author is a relationship method in the Book class
  • kristoffer
    kristoffer over 3 years
    This looks amazing! Thanks for your input!
  • Luciano
    Luciano over 2 years
    I think that ->get() is not needed at all within the closure