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!


About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Get The best In Web dev

Get The best In Web dev

Join dunebook and recieve best in Angular, React, Vue, Python, Java & more. Directly to your inbox once a week FREE !

You have Successfully Subscribed!

Pin It on Pinterest