0
0
Laravelframework~8 mins

Eager loading (with) in Laravel - Performance & Optimization

Choose your learning style9 modes available
Performance: Eager loading (with)
HIGH IMPACT
Eager loading reduces the number of database queries, improving page load speed and interaction responsiveness.
Loading related data for multiple records
Laravel
$posts = Post::with('author')->get();
foreach ($posts as $post) {
    echo $post->author->name;
}
Loads all authors in a single query before looping, reducing database calls drastically.
📈 Performance GainSingle query for posts and authors, reducing queries from N+1 to 2, improving LCP.
Loading related data for multiple records
Laravel
foreach ($posts as $post) {
    echo $post->author->name;
}
This triggers a separate query for each post to fetch the author, causing the N+1 query problem.
📉 Performance CostTriggers N+1 database queries, blocking rendering until all queries complete.
Performance Comparison
PatternDatabase QueriesNetwork RequestsServer Response TimeVerdict
Lazy loading (accessing relations inside loop)N+1 queriesMultipleHigh[X] Bad
Eager loading with 'with' method2 queriesFewLow[OK] Good
Rendering Pipeline
Eager loading reduces database query count, so the server sends data faster to the browser, improving the critical rendering path.
Data Fetching
Server Response
Rendering
⚠️ BottleneckDatabase query execution and network latency
Core Web Vital Affected
LCP
Eager loading reduces the number of database queries, improving page load speed and interaction responsiveness.
Optimization Tips
1Always use eager loading when accessing related data in loops.
2Avoid lazy loading inside loops to prevent multiple database queries.
3Check query count in DevTools Network tab to verify eager loading effectiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using eager loading in Laravel?
AReduces the number of database queries
BIncreases the number of database queries
CDelays data fetching until needed
DCaches data on the client side
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and count the number of API or page requests related to data fetching.
What to look for: Fewer database-related requests or API calls indicate effective eager loading.