In Laravel, Eager Loading and Lazy Loading are concepts used when working with Eloquent relationships to load related models. They determine when and how related data is retrieved from the database. Let’s break them down:
1. Lazy Loading
Lazy Loading is the default behavior in Laravel. Related data is loaded only when it is accessed for the first time.
Example:
$users = User::all(); // Only users are fetched
foreach ($users as $user) {
echo $user->posts->count(); // Posts are loaded here, per user
}
What happens here:
- First, Laravel executes
SELECT * FROM users. - Then, for each user, it executes a separate query to get posts:
SELECT * FROM posts WHERE user_id = ?. - This can lead to the N+1 query problem, which is inefficient if you have many users.
Pros:
- Only loads related data when needed.
- Can save memory if you don’t need related data.
Cons:
- Can result in many queries (N+1 problem), slowing down your app.
2. Eager Loading
Eager Loading loads the related data upfront, in the same query (or optimized queries), avoiding multiple database hits.
Example:
$users = User::with('posts')->get(); // Users + their posts are fetched in 2 queries
foreach ($users as $user) {
echo $user->posts->count(); // No extra queries
}
What happens here:
- Laravel executes two queries:
SELECT * FROM usersSELECT * FROM posts WHERE user_id IN (...)
- All posts for all users are loaded in one go, avoiding multiple queries.
Pros:
- Prevents N+1 query problem.
- More efficient for large datasets.
Cons:
- Loads related data even if not needed, which may increase memory usage.
Key Difference
| Feature | Lazy Loading | Eager Loading |
|---|---|---|
| When data is loaded | On demand (when accessed) | Upfront (when querying the parent) |
| Queries executed | One query per parent (N+1 problem) | Few optimized queries |
| Performance | Can be slow for many parents | Faster for multiple parents |
| Syntax | $user->posts | User::with('posts')->get() |
✅ Rule of thumb: Use eager loading whenever you know you will need the related data, especially in loops, to improve performance.
