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 🚀