Advertisement
Intermediate PHP, Eloquent ORM & Doctrine ORM

What is eager loading in Eloquent, and how does it help solve the N plus one query performance problem?

Short answer

The N plus one query problem occurs when retrieving a list of records and then separately querying related data for each individual record in a loop, resulting in one initial query plus an additional query for every single record, which can severely degrade performance, and…

Save PHP mock interview
Advertisement
AModel answer
The N plus one query problem occurs when retrieving a list of records and then separately querying related data for each individual record in a loop, resulting in one initial query plus an additional query for every single record, which can severely degrade performance, and eager loading, using the with method, solves this by retrieving the main records along with all their related data in just a couple of efficient queries total, regardless of how many records are actually being retrieved.
$users = User::with('orders')->get();
foreach ($users as $user) {
    echo count($user->orders);
}
Real-world example
A dashboard displaying one hundred users along with their order counts uses eager loading to retrieve all users and their related orders in just two queries total, instead of the one hundred and one queries that would otherwise result from loading each user's orders separately inside the loop.
Likely follow-ups
  • How do you detect the N plus one query problem in an existing application?
  • Can you eager load multiple relationships at once, or nested relationships?
Related topics