Eager Loading vs Lazy Loading — The N+1 Problem
The N+1 problem is the most common performance issue in Laravel applications. When you loop through posts and access $post->user, Laravel runs a separate query for EACH post's user — 1 query for posts + N queries for users. Eager loading (with()) pre-loads relationships in 2 queries total regardless of N.
N+1 Problem and Eager Loading
// THE PROBLEM: N+1 queries (1 + 100 = 101 queries!)
$posts = Post::all(); // 1 query: SELECT * FROM posts
foreach ($posts as $post) {
echo $post->user->name; // 1 query PER post: SELECT * FROM users WHERE id = ?
}
// THE SOLUTION: Eager loading (only 2 queries!)
$posts = Post::with('user')->get();
// Query 1: SELECT * FROM posts
// Query 2: SELECT * FROM users WHERE id IN (1, 2, 3, ...)
foreach ($posts as $post) {
echo $post->user->name; // No additional query!
}
// Eager load multiple relationships
$posts = Post::with(['user', 'tags', 'comments'])->get();
// Nested eager loading
$posts = Post::with('comments.user')->get();
// Loads posts → comments → each comment's user
// Constrained eager loading
$posts = Post::with(['comments' => function ($query) {
$query->where('approved', true)->latest()->limit(5);
}])->get();
// Prevent lazy loading in development (catch N+1 bugs)
// In AppServiceProvider:
Model::preventLazyLoading(!app()->isProduction());Why N+1 Matters
A page displaying 100 posts with author names generates 101 database queries without eager loading vs 2 queries with it. At scale, this is the difference between a 200ms page load and a 5-second page load. Enable Model::preventLazyLoading() in development to throw exceptions whenever lazy loading occurs — this forces you to use eager loading consistently and prevents N+1 bugs from reaching production.
Laravel follows the MVC pattern with elegant routing and middleware
Tip
Tip
Practice Eager Loading vs Lazy Loading The N1 Problem in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Practice Task
Note
Practice Task — (1) Write a working example of Eager Loading vs Lazy Loading The N1 Problem from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Eager Loading vs Lazy Loading The N1 Problem is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.