What is lazy loading in Laravel?
Lazy loading in Laravel is a technique to improve resource efficiency by loading related data only when it is actually needed. This helps reduce memory usage and unnecessary database queries, making your application more scalable and responsive.
How Lazy Loading Works
In Laravel, lazy loading is the default behavior for Eloquent relationships. Instead of fetching all related data immediately, Laravel waits until you explicitly access that data. For example, if a blog post has 10 comments, the comments are not loaded from the database until the user views them.
Potential Issues: N+1 Query Problem
While lazy loading reduces memory usage for single records, it can cause the N+1 query problem. This happens when Laravel executes one query to fetch the main data and then an additional query for each related item. With many records, this can drastically slow down your application.
Solution: Eager Loading & Lazy Eager Loading
Laravel provides strategies to avoid N+1 problems:
| Strategy | Method | Use Case |
|---|---|---|
| Lazy Loading | $post->comments | Single model instances where the relation might not be needed immediately. |
| Eager Loading | Post::with('comments')->get() | Collections/lists where the relation will definitely be needed (prevents N+1 queries). |
| Lazy Eager Loading | $post->load('comments') | Load related data after a specific conditional check on the model. |
Modern Laravel 12 Workflow: Strict Mode
To prevent performance regressions, senior developers now disable lazy loading in development by adding the following to AppServiceProvider:
public function boot(): void
{
Model::preventLazyLoading(! app()->isProduction());
}
This ensures that any accidental lazy load in development throws an exception, forcing the use of eager loading.
Refined Tips for Lazy Loading
- When eager loading, select only the columns you need:
with('comments:id,post_id,body'). - Use
whenLoaded()in API Resources to avoid triggering lazy loads accidentally. - Balance lazy and eager loading: use lazy loading for single records, eager loading for collections.
Conclusion
Lazy loading in Laravel is useful for managing memory and deferring unnecessary queries, but it can hurt performance on collections if not managed properly. By using eager loading, lazy eager loading, and strict mode in development, developers can prevent N+1 problems and ensure efficient, scalable applications.
Related Answers
Still need help?
Talk to our Laravel experts
We've handled GDPR/CCPA compliance for dozens of EU & US Laravel.
