Start free trial
Start free trial Log in

14-day free trial. No credit card.

Eager vs lazy loading in Eloquent

  • Glossary
  • 3 minute read

What's the difference between eager and lazy loading in Laravel Eloquent?

Lazy loading fetches a relationship on demand, firing one query per access, which becomes N+1 when accessed inside a loop. Eager loading uses with() to fetch all related records up front in one additional query with WHERE IN, regardless of parent count. Eager is faster for collections; lazy is fine for single parents. Use preventLazyLoading in development to catch N+1 as a hard error.

Updated

This is one of the most useful database habits to get right in Laravel, because the wrong choice is the N+1 query, and the N+1 is a common reason a Laravel page is slow. The mechanics are simple once you've seen them, and the fix is usually one method call. The hard part is noticing you needed it.

Lazy loading, by default

Eloquent loads relationships on demand. Accessing $user->posts fires a query at the moment of access:

$users = User::take(100)->get();  // 1 query

foreach ($users as $user) {
    echo $user->posts->count(); // 1 query per user, 100 total
}

// Total: 1 + 100 = 101 queries → N+1

Eager loading with with()

$users = User::with('posts')->take(100)->get();  // 2 queries total

foreach ($users as $user) {
    echo $user->posts->count(); // no query fires: already loaded
}

// Total: 2 queries, regardless of user count

Under the hood: one SELECT * FROM users LIMIT 100, then one SELECT * FROM posts WHERE user_id IN (1, 2, 3, ..., 100). Eloquent wires the posts back to their users in-memory.

Nested relationships

// Load users + their posts + each post's comments + each comment's author
User::with('posts.comments.author')->get();

// 4 queries total:
// 1. SELECT * FROM users
// 2. SELECT * FROM posts WHERE user_id IN (...)
// 3. SELECT * FROM comments WHERE post_id IN (...)
// 4. SELECT * FROM users WHERE id IN (...)  -- comment authors

Four queries for any number of rows. Lazy loading the same tree runs one query for the users, one per user, one per post and one per comment, which adds up to thousands on a busy page.

Constraining eager loads

// Only eager-load published posts
User::with(['posts' => fn ($q) => $q->where('published', true)])->get();

// Only specific columns (reduces memory)
User::with('posts:id,user_id,title')->get();

// Load counts without the rows themselves
User::withCount('posts')->get();

preventLazyLoading: catch N+1 in dev

app/Providers/AppServiceProvider.php
use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
    Model::preventLazyLoading(! $this->app->isProduction());
}

In non-production, lazy loading a relationship on a model that came from a multi-row result throws LazyLoadingViolationException. A single model from find() or first() can still lazy load. You're forced to either eager-load or explicitly $user->loadMissing('posts'). Catches N+1 as a bug during development rather than as a slow page in production.

Don't enable it in production as written. A missed eager-load becomes a 500 for real users instead of a slow page. If you want the signal in production, enable it everywhere and register a handler with Model::handleLazyLoadingViolationUsing() that logs the violation instead of throwing.

When the models are already in hand: load()

with() works when you control the query. Sometimes you don't: a collection gets passed into a method, or you fetched it before you knew you'd need the relationship. load() is the after-the-fact version:

$users = User::take(100)->get();   // already fetched, no relations

// ...later, once you know you need them:
$users->load('posts');             // one batched query, not 100

// inside reusable code, prefer loadMissing: it skips models
// that already have the relation loaded:
$users->loadMissing('posts');

Rule of thumb: with() when you're writing the query, load() or loadMissing() when the models already exist.

When lazy loading is actually fine

On a single model, not a collection: $user = User::find(1); $user->posts; fires one query. No N+1. The problem only materializes with loops over collections.

Find the lazy loads in your production requests

NightOwl doesn't flag lazy loading, but every request's timeline gives identical SQL the same colour and a Duplicates tab that lists only the repeated queries. A relationship loaded inside a loop shows up there as the same statement run once per row.

No credit card needed.

Frequently asked questions

Anything else, write to support@usenightowl.com

What's the difference between eager and lazy loading in Laravel?

Lazy loading fetches related models on demand: each access to a relationship fires a separate query. Eager loading fetches the relationship upfront with a single extra query using WHERE IN. Eager loading is faster for most cases because it avoids the N+1 problem; lazy loading is simpler and fine when you only access one parent's relations.

How do I eager load in Laravel?

Use with() on the query. User::with('posts')->get() loads all users and their posts in two queries regardless of user count: one SELECT FROM users, one SELECT FROM posts WHERE user_id IN (...). Without with(), accessing $user->posts on each user fires one query per user, which is N+1.

Can I eager load nested relationships?

Yes. User::with('posts.comments.author')->get() loads users + posts + comments + authors in four queries total, regardless of how many rows. Be careful with deep nesting. It's still better than N+1 but the query set can return a lot of data. At some point you want to denormalize or paginate.

What's preventLazyLoading?

A Laravel feature that throws an exception when a model that came from a multi-row result lazy loads a relationship, forcing you to explicitly eager load. A model fetched on its own is left alone. Call Model::preventLazyLoading() in AppServiceProvider::boot() in local/staging environments. Catches N+1s as development-time errors instead of as production performance bugs.

When is lazy loading actually fine?

When you're working with a single parent model, not a collection. If you loaded one $user and access $user->posts, that's one query, not N+1. If you loaded a collection of users and access ->posts on each one, that's N+1. preventLazyLoading draws the same line: it only throws for models that came from a multi-row result.

How do I spot missing eager loads in production with NightOwl?

NightOwl records every query per request but doesn't flag lazy loading itself. On a request's timeline, identical SQL shares a colour and the Duplicates tab lists only the repeated queries. When a request fired 1,000 select * from posts where posts.user_id = ? and posts.user_id is not null queries, that's a classic N+1 waiting to be fixed with with('posts'). The Queries page shows each pattern's call count across production traffic, not just local dev.

Keep reading

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial