EAGER LOADING

Jan 07, 2024 Copy Link

When working on a Laravel project, we may accidentally commit a 1 + N query problem.

 

Before embarking on working on that problem, I recommend using laravel-debugbar package for more query analysis.

 

Let's assume that we have ten records in the `cars` table and every car belongs to only one user, we want to show the car owner, so you may write a code as follows:

 

use App\Models\Car;

$cars = Car::get();

foreach ($cars as $car) {
    dump("{$car->user->name} owns {$car->number_plate}.");
}

 

When you open the debugbar you will find out that you requested eleven queries against the database. The first query was getting all the cars' records, and the other ten queries were inside the for loop that is because we triggered a database query to get the user's name on each car iteration, which Laravel called LazyLoading

 

To overcome that big problem, you should use the EagerLoading feature in Laravel via `with` eloquent method:

 

use App\Models\Car;

$cars = Car::with('user')->get();

foreach ($cars as $car) {
    dump("{$car->user->name} owns {$car->number_plate}.");
}

 

When you open the debugbar now, you will find out that you requested only two queries against the database

 

Boom...The problem is solved now 🚀

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autol...

    FREE

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE