Laravel & Ecosystem (50 Qs)•Part 1: Architecture, Service Container & Request Lifecycle (1 - 10)
What is the N+1 Query Problem in Eloquent and how do you resolve it?
senior LevelCode ExampleLifecycleDocker & ContainersSystem Design
In Simple Words: Occurs when querying parent records and accessing their relationships in a loop without eager loading:
php
// BAD: 1 query for users + 100 queries for profiles = 101 SQL queries!
$users = User::all();
foreach ($users as $user) {
echo $user->profile->bio; // Triggers a separate SQL query per user!
}
// GOOD: Eager Loading using with() = Strictly 2 SQL queries!
$users = User::with('profile')->get();
// SELECT * FROM users;
// SELECT * FROM profiles WHERE user_id IN (1, 2, 3, ...);
- In Laravel 10+, prevent it globally in development:
Model::preventLazyLoading(!app()->isProduction());.