Tutorials , code & Inspiration

Dealing with Eager loading and the N + 1 problem in laravel

Every powerful tool must be used wisely. Relationships in Eloquent are no exception to the rule. Actually, one of the most common problems in using Eloquent is the N + 1 problem. To explain it, I will use an example as usual.

Let’s suppose that I am showing some data for the first 100 books. Starting with this data, I also want to print the author name for every single book.

Using what we’ve learned before now, here’s the code:

  $books = \App\Book::take(100)->get();

  foreach($books as $book)
    $author = $book->author;

    echo $author->first_name . ' ' . $author->last_name;

Even if the syntax is simple, under the hood, Eloquent is performing 101 queries! The first one is to get the list of the 100 books, then a query for every book to get the author. This is not exactly performance friendly, right?

Don’t worry, there is a solution!


prevChapter 1 of 4

Pin It on Pinterest