Eliminate Laravel N+1 Queries with Eloquent Eager Loading
Learn how Eloquent's with() method loads relationships in a single query instead of one per row, with a worked example and verification steps.
04 Oct 2025, 03:45 UTC

The loop that kills your database
You build an index page that lists 20 blog posts. In the Blade template, you print each post's author:
@foreach ($posts as $post)
{{ $post->title }} by {{ $post->author->name }}
@endforeach
That looks harmless, but Eloquent lazy loads author the first time you touch it. Lazy loading means Eloquent fetches related rows only when you access the property, not when you fetch the parent. With 20 posts, the page runs one query for the posts and one separate query for each author: roughly 21 round trips to the database instead of two.
Eager load relationships up front
Add with('author') to the query so Eloquent loads the related users in a single additional query, using a WHERE id IN (...) clause against the parent IDs. The page then runs about two queries regardless of whether you return 20 posts or 200.
Before: lazy loading in a controller
use App\Models\Post;
// routes/web.php or a controller method
$posts = Post::latest()->paginate(20);
In the template, $post->author triggers a query per row.
After: eager loading with with()
$posts = Post::with('author')->latest()->paginate(20);
Eloquent now executes one query for posts and one for the related authors. The relationship is already attached to each model when the template accesses it.
Check the query count
Run this in a local route closure or test, not in production, because the query log stores every statement in memory:
use Illuminate\Support\Facades\DB;
DB::enableQueryLog();
$posts = Post::with('author')->get();
foreach ($posts as $post) {
// Accessing the relationship should not trigger new queries
_ = $post->author->name;
}
dd(DB::getQueryLog());
Run the same block without with('author') and compare count(DB::getQueryLog()). You should see roughly one query for the posts plus one per author before eager loading, and two total after. DB::listen is another option if you want to inspect the actual SQL and confirm the second query uses WHERE id IN (...).
Nested relationships and constraints
Use dot notation for deeper nesting:
Post::with('author.profile')->get();
If you need to filter or select columns on the eager-loaded relationship, pass a closure instead of relying on constraints after with(). A where on the parent query does not filter what gets eager loaded:
// Does NOT limit which authors are loaded
$posts = Post::where('published', true)->with('author')->get();
// Limits authors to active users only
$posts = Post::with(['author' => function ($query) {
$query->where('active', true);
}])->get();
Trade-offs and limits
- Eager loading hydrates every related model into memory. Loading hundreds of posts with large nested collections can use more RAM than lazy loading.
- Do not eager load every relationship "just in case." Unused columns and rows make responses slower than selective loading.
- Use
withCount('comments')when you only need the number of related models. It avoids hydrating full comment objects.
Verify before you deploy
Seed 20 parents with related children, request the index page, and compare the query log before and after adding with(). Expect the count to fall from roughly N + 1 to two. If the count does not drop, check whether the relationship is accessed inside a closure or dynamically, which can bypass eager loading.
Make it a habit
Whenever you loop over an Eloquent collection and touch a relationship, add with() to the query and check the query log. It is one of the fastest ways to remove database round trips without changing your schema.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.