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.
Seeing the N+1 Problem in Real Code
Take a blog listing that shows each post with its author's name. The lazy version looks innocent:
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 extra query per post
}
With 50 posts this runs 51 queries. The eager version asks for the authors up front:
$posts = Post::with('author')->get(); // 2 queries in total
foreach ($posts as $post) {
echo $post->author->name; // no new query
}
Behind the scenes Eloquent runs one query for the posts, collects every author_id, runs a single WHERE id IN (...) query for the authors, and matches them in memory. The number of queries stays the same whether you show ten posts or a thousand.
Useful Eager Loading Variations
| Need | Code |
|---|---|
| Several relationships | Post::with(['author', 'tags'])->get() |
| Nested relationships | Post::with('comments.user')->get() |
| Only certain columns | Post::with('author:id,name')->get() |
| Filtered related rows | Post::with(['comments' => fn ($q) => $q->where('approved', true)])->get() |
| Just a count | Post::withCount('comments')->get(), then use $post->comments_count |
| Load after fetching | $posts->load('author') |
When selecting columns, always include the primary key and any foreign key, otherwise Eloquent cannot match related records and the relationship comes back empty. The load() method, sometimes called lazy eager loading, is handy when you decide to load a relationship only after checking a condition.
Catching N+1 Queries Early
Laravel can refuse lazy loading during development so mistakes show up as errors instead of slow pages. Add this to the boot() method of AppServiceProvider:
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! app()->isProduction());
}
Now any accidental lazy load throws an exception locally, while production users are never affected. Tools such as Laravel Debugbar or Laravel Telescope show the number of queries per request, which is the quickest way to spot a loop that suddenly fires hundreds of them.
When Lazy Loading Is Still Fine
- Loading a relationship for a single model, for example one post on its detail page.
- A relationship used only in a rare branch, where eager loading would waste a query most of the time.
Also avoid the opposite mistake: adding many relationships to a model's $with property so they load on every query. That hides cost and fetches data many pages never use. Eager load explicitly where the data is needed.
A simple review habit helps: whenever a Blade view or API resource loops over a collection, check which relationships are used inside the loop and make sure the controller loads them with with(). Doing this in code review catches most performance problems before they ever reach users.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.