Skip to content

Laravel 5 Eloquent lazy eager loading

Sometimes you may need to eager load a relationship after the parent modal has already been retrieved. For Example this may be very useful if you need to dynamically decide whether to load related models or not, or in combination with caching.

  $books = App\Book::all();

  if($someCondition) {
     $books->load('author', 'publisher');
  }

You can also set additional query constraints on the eager loading query, by passing a Closure to the load method.

  $books = App\Book::all();

  if($someCondition) {

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

  }

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments