Laravel - Relationships - Lazy Eager Loading

Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models:

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

If you need to set additional query constraints on the eager loading query, you may pass an array keyed by the relationships you wish to load. The array values should be closure instances which receive the query instance:

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

To load a relationship only when it has not already been loaded, use the loadMissing method:

    
    $book->loadMissing('author');