0
0
Laravelframework~10 mins

Lazy loading and N+1 prevention in Laravel - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lazy loading and N+1 prevention
Start Query for Posts
Lazy Load Posts
Access Related Comments?
No Extra Query
N+1 Problem if in Loop
Use Eager Loading to Prevent N+1
Single Query for Comments
Display Data
End
This flow shows how lazy loading fetches related data only when accessed, which can cause many queries (N+1 problem), and how eager loading prevents this by fetching all needed data upfront.
Execution Sample
Laravel
use App\Models\Post;

$posts = Post::all();

foreach ($posts as $post) {
    echo $post->comments->count();
}
This code fetches all posts, then for each post accesses its comments, triggering lazy loading and causing N+1 queries.
Execution Table
StepActionQuery ExecutedResultNotes
1Fetch all postsSELECT * FROM postsCollection of postsOne query to get all posts
2Start loop: first postNo query yetAccess first post objectNo comments queried yet
3Access comments of first postSELECT * FROM comments WHERE post_id = 1Comments collection for post 1Lazy loading triggers query
4Output comments count for first postNo queryNumber of comments for post 1Count displayed
5Loop: second postNo query yetAccess second post objectNo comments queried yet for post 2
6Access comments of second postSELECT * FROM comments WHERE post_id = 2Comments collection for post 2Lazy loading triggers query again
7Output comments count for second postNo queryNumber of comments for post 2Count displayed
8Repeat for all postsOne query per post for commentsComments collectionsN+1 queries total
9End loopNo queryAll posts processedN+1 problem evident
💡 Loop ends after all posts processed; N+1 queries executed due to lazy loading inside loop.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 6Final
$postsnullCollection of all postsSame collectionSame collectionSame collection
$postnullFirst post objectFirst post objectSecond post objectLast post object
$post->commentsnullnullComments collection for post 1Comments collection for post 2Comments collection for last post
Key Moments - 3 Insights
Why does accessing $post->comments inside the loop cause many queries?
Because lazy loading fetches related comments only when accessed, so each post triggers a separate query as shown in steps 3 and 6 of the execution_table.
How can we prevent the N+1 problem in this example?
By using eager loading (e.g., Post::with('comments')->get()), which fetches all posts and their comments in just two queries, avoiding the repeated queries inside the loop.
Does lazy loading always cause N+1 queries?
No, lazy loading only causes N+1 queries when related data is accessed repeatedly in a loop, as shown in the execution_table steps.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what query runs at step 6?
ASELECT * FROM comments WHERE post_id = 2
BSELECT * FROM posts
CSELECT * FROM comments WHERE post_id = 1
DNo query runs
💡 Hint
Check the 'Query Executed' column at step 6 in the execution_table.
At which step does the N+1 problem become clear?
AStep 1
BStep 8
CStep 3
DStep 9
💡 Hint
Look for the step mentioning 'One query per post for comments' in the Notes column.
If we use eager loading, how would the number of queries change?
AIt would stay the same
BIt would increase
CIt would reduce to two queries
DIt would reduce to zero queries
💡 Hint
Refer to the key_moments section explaining eager loading benefits.
Concept Snapshot
Lazy loading fetches related data only when accessed, causing many queries if done inside loops (N+1 problem).
Eager loading fetches all related data upfront with fewer queries.
Use Post::with('comments')->get() to prevent N+1.
Avoid accessing relations inside loops without eager loading.
This improves performance by reducing database queries.
Full Transcript
This visual execution trace shows how Laravel's lazy loading works by fetching related comments only when accessed on each post. The example code fetches all posts, then loops through them, accessing comments for each post. This triggers a separate query per post for comments, causing the N+1 problem. The execution table details each step, showing queries run and data accessed. The variable tracker shows how variables change during execution. Key moments clarify why lazy loading inside loops causes many queries and how eager loading prevents this by fetching all related data in fewer queries. The quiz tests understanding of query steps and N+1 prevention. The snapshot summarizes the concept for quick reference.