0
0
Laravelframework~8 mins

One-to-many (hasMany) in Laravel - Performance & Optimization

Choose your learning style9 modes available
Performance: One-to-many (hasMany)
MEDIUM IMPACT
This affects how many database queries are run and how much data is loaded into memory, impacting page load speed and responsiveness.
Loading a model with many related child models
Laravel
<?php
$posts = App\Models\Post::with('comments')->get();
foreach ($posts as $post) {
    echo $post->comments->count();
}
Eager loading fetches all comments in one query, reducing database calls.
📈 Performance GainSingle query for all related comments, reducing queries from N+1 to 2.
Loading a model with many related child models
Laravel
<?php
$posts = App\Models\Post::all();
foreach ($posts as $post) {
    echo $post->comments->count();
}
This triggers a separate database query for each post to load comments (N+1 query problem).
📉 Performance CostTriggers N+1 queries, causing slow page load and high database load.
Performance Comparison
PatternDatabase QueriesMemory UsageResponse TimeVerdict
Lazy loading (N+1 queries)N+1 queriesHigher due to repeated loadsSlower with many related items[X] Bad
Eager loading (with)2 queriesLower and predictableFaster and scalable[OK] Good
Rendering Pipeline
The database queries run before rendering. Multiple queries increase server response time, delaying HTML delivery and LCP.
Data Fetching
Server Response
HTML Rendering
⚠️ BottleneckDatabase query count and response time
Core Web Vital Affected
LCP
This affects how many database queries are run and how much data is loaded into memory, impacting page load speed and responsiveness.
Optimization Tips
1Avoid lazy loading in loops to prevent N+1 query problems.
2Use eager loading (with) to batch fetch related models efficiently.
3Monitor database query count to keep server response fast.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with lazy loading related models in a one-to-many relationship?
AIt caches data too aggressively, causing stale content.
BIt triggers many small database queries, slowing down page load.
CIt loads all data in one big query, causing memory issues.
DIt blocks rendering with heavy CSS styles.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter XHR requests, and count the number of API/database calls triggered when loading the page.
What to look for: Multiple repeated queries for related data indicate N+1 problem; fewer grouped queries indicate good eager loading.