Eager Loading and Lazy Loading
How and when Eloquent actually fetches related data has a big impact on application performance. Laravel supports two approaches — lazy loading and eager loading — and choosing the right one avoids one of the most common Eloquent performance pitfalls.
Lazy Loading
By default, relationships are loaded lazily: the related data is only fetched from the database the moment it's actually accessed. This is convenient, but it becomes a problem inside a loop, where accessing a relationship on each item triggers a brand-new query every time — known as the N+1 query problem.
Eager Loading
Eager loading solves this by fetching a model's relationships upfront, in a small, fixed number of queries, using the with() method. Instead of one query per record, related data for an entire collection is retrieved in just one or two additional queries.
| Approach | Query Behavior | Best For |
|---|---|---|
| Lazy loading | One query per relationship access | Accessing a relationship occasionally, outside a loop |
Eager loading (with()) | A small, fixed number of queries upfront | Looping through a collection and using its relationships |
Spotting and Preventing N+1 Issues
- A loop that accesses a relationship on every item is a strong warning sign
- Laravel can be configured to throw an exception when lazy loading occurs unexpectedly
- Nested relationships can be eager loaded together using dot notation
Eager loading works well for one-to-many and many-to-many relationships alike, but many-to-many connections have an extra piece worth understanding on their own: the pivot table.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
