EAGER LOADING
Jan 07, 2024 Copy Link
When we are working on a Laravel project, you may commit a 1 + N query problem accidentally
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 owner of each car, so you may write a code as follows:
use App\Models\Car;
$cars = Car::get();
foreach ($cars as $car) {
dump("The owner of {$car->type} is {$car->user->name}.");
}
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("The owner of {$car->type} is {$car->user->name}.");
}
When you open the debugbar
now, you will find out that you request only two queries against the database
Boom...The problem is solved now 🚀