← Back to Course

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.

ApproachQuery BehaviorBest For
Lazy loadingOne query per relationship accessAccessing a relationship occasionally, outside a loop
Eager loading (with())A small, fixed number of queries upfrontLooping through a collection and using its relationships

Spotting and Preventing N+1 Issues

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.

Explore Course