Eager vs Lazy Loading in Laravel (Clear, Practical Guide)

Speed up your Laravel app by mastering the difference between eager and lazy loading. Avoid N+1 queries with clear examples.
Introduction
Loading relationships in Laravel can either make your app fly or crawl.
This guide breaks down eager vs lazy loading in Laravel, how they impact performance, and when to use each — with real examples.
🐢 What Is Lazy Loading?
What it means: Laravel loads related data only when you access it — not before.
Example:
$posts = Post::all(); // no relations yet
foreach ($posts as $post) {
echo $post->user->name; // triggers a separate query per post
}
🔴 Problem: This causes the N+1 query issue — one query for all posts, then one extra for each post’s user.
⚡ What Is Eager Loading?
What it means: You tell Laravel up front to load relationships in the same query.
Example:
$posts = Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // already loaded
}
✅ Advantage: Cuts the number of queries down to 2 (posts + users). Much faster for lists.
🔄 When Should You Use Each?
Use lazy loading when:
- You only need the relation in rare cases
- You’re loading just one model, not a list
Use eager loading when:
- You’re looping over many models with related data
- You care about performance and want to avoid N+1
🎯 Bonus: Eager Load Multiple or Nested Relations
Multiple relations:
$posts = Post::with(['user', 'comments'])->get();
Nested relations:
$posts = Post::with('comments.user')->get();
🧪 Pro Tip: Debug with Laravel Debugbar or Telescope
They’ll show you exactly how many queries are being run, and if you’re accidentally lazy-loading inside a loop.
Conclusion
Lazy loading is simple, but dangerous in loops. Eager loading is your best friend for performance — if you use it smartly.
💡 Tip: Always check your query count when dealing with Eloquent relationships.
What’s Next?
- Want real project examples where eager loading saved performance?
- Need help optimizing a slow Laravel app?
Check out more Laravel deep-dives on my blog:
🔗 https://mostefa-boudjema.vercel.app/blog





