Search code examples
phplaraveleloquenteager-loading

Can I manually eager load a model with data in Laravel Eloquent?


For example say I have Book and Author models. I'd eager load the authors like this:

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

But I have already fetched the list of authors with Author::all() in order to display them elsewhere on the page (a select field for filtering). So now Laravel executes 3 queries:

select * from authors;
select * from books;
select * from authors where id in (1, 2, 3, ...);

The third query is obviously superfluous since I already have the authors. Is there some way to pass my $authors Collection into my Book query? Searched through the docs and API and can't find anything.


Solution

  • You can use this custom code

    $authors = Author::get();
    $books = Book::get();
    
    foreach ($books as $book) {
        $author = $authors->where('id', $book->author_id)->first();
        $book->setRelation('author', $author);
    }