Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel eager loading nested relationship
    Laravel eager loading nested relationships Eloquent dot notation column selection constraints load method PHP


Laravel eager loading nested relationship


To eager load nested relationships in Laravel, you can use dot notation to specify the nested relationships you want to load. Here's an example of how to eager load a book's author and the author's contacts in one Eloquent statement:

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

You can also specify which columns to include for each relationship:

php
$books = App\Book::with('author:id,name', 'author.contacts:id,phone')->get();

This will only load the `id` and `name` columns from the `authors` table, and the `id` and `phone` columns from the `contacts` table.

To add constraints to the eager loading query, you can pass a closure to the `with` method:

php
$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();

This will only eager load posts where the `title` column contains the word "first".

If you need to eager load a relationship after the parent model has already been retrieved, you can use the `load` method:

php
$books = App\Book::all();
if ($someCondition) {
    $books->load('author', 'publisher');
}

You can also add constraints to the `load` method:

php
$books->load(['author' => function ($query) {
    $query->orderBy('published_date', 'asc');
}]);

Remember to always include the foreign key columns when eager loading nested relationships, or the nested models may not load at all[4].

Citations:
[1] https://stackoverflow.com/questions/35490728/laravel-eloquent-eager-loading-of-multiple-nested-relationships
[2] https://stackoverflow.com/questions/35490728/laravel-eloquent-eager-loading-of-multiple-nested-relationships/53205641
[3] https://www.youtube.com/shorts/jCya8PUXox0
[4] https://laravel.com/docs/5.2/eloquent-relationships
[5] https://www.youtube.com/watch?v=p3zoHlMe1xw