Eloquent N+1 Optimization for Laravel Developers | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Eloquent Query Optimization: Slaying N+1 Problems at Scale

 Eloquent Query Optimization: Slaying N+1 Problems at Scale
===========================================================

 N+1 queries silently kill Laravel app performance. This guide digs into eager loading strategies, query deduplication, and Eloquent internals to help you write queries that stay fast as data grows.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 8 Aug 2026 · Updated 8 Aug 2026 · 4 min read

ShareCopy linkCopied

 ![Eloquent Query Optimization: Slaying N+1 Problems at Scale](https://cdn.msaied.com/523/a12bd8c82544aafcd6de50ff8c076141.png) 

  On this page +1. [The N+1 Problem Is Not Just a Beginner Mistake](#the-n1-problem-is-not-just-a-beginner-mistake)
2. [Reproducing the Classic Case](#reproducing-the-classic-case)
3. [Detecting Queries You Did Not Know Were There](#detecting-queries-you-did-not-know-were-there)
4. [Subquery Selects: Pulling Aggregates Without Extra Queries](#subquery-selects-pulling-aggregates-without-extra-queries)
5. [Lazy Eager Loading vs. load() vs. loadMissing()](#lazy-eager-loading-vs-codeloadcode-vs-codeloadmissingcode)
6. [Preventing Lazy Loading Globally in Development](#preventing-lazy-loading-globally-in-development)
7. [Chunking and Cursor Iteration for Large Result Sets](#chunking-and-cursor-iteration-for-large-result-sets)
8. [Key Takeaways](#key-takeaways)

 The N+1 Problem Is Not Just a Beginner Mistake
----------------------------------------------

Every Laravel developer learns about `with()` early on, but N+1 queries keep appearing in production codebases — often in places that look perfectly reasonable at first glance. The real danger is not the obvious loop; it is the subtle one hiding inside a resource transformer, a Blade component, or a policy check.

### Reproducing the Classic Case

```php
// Fetches 1 query for posts, then 1 per post for the author — classic N+1
$posts = Post::all();

foreach ($posts as $post) {
    echo $post->author->name; // lazy-loads author every iteration
}

```

The fix is well-known:

```php
$posts = Post::with('author')->get();

```

But what about conditional relationships, or relationships accessed three layers deep inside a resource class?

### Detecting Queries You Did Not Know Were There

Install Laravel Telescope or use the `DB::listen` trick in a test:

```php
$queries = [];
DB::listen(fn ($q) => $queries[] = $q->sql);

$resource = new PostCollection(Post::with('author')->paginate(20));
$resource->toArray(request());

dump(count($queries)); // should be 2, not 21

```

For CI, the `assertQueryCount` helper from `pestphp/pest-plugin-laravel` is invaluable:

```php
it('loads posts without N+1', function () {
    Post::factory(20)->for(User::factory(), 'author')->create();

    $count = 0;
    DB::listen(fn () => $count++);

    Post::with('author')->get()->each(fn ($p) => $p->author->name);

    expect($count)->toBe(2);
});

```

### Subquery Selects: Pulling Aggregates Without Extra Queries

A common pattern is showing the latest comment date on a post list. The naive approach eager-loads all comments just to grab `max(created_at)`. Use a subquery select instead:

```php
$posts = Post::select('posts.*')
    ->addSelect([
        'latest_comment_at' => Comment::select('created_at')
            ->whereColumn('post_id', 'posts.id')
            ->latest()
            ->limit(1),
    ])
    ->get();

// Access as a plain attribute — zero extra queries
echo $posts->first()->latest_comment_at;

```

This emits a single SQL query with a correlated subquery. On indexed columns it is extremely efficient and far cleaner than `withCount` + `withMax` chains.

### Lazy Eager Loading vs. `load()` vs. `loadMissing()`

When you receive a model that may or may not have a relationship already loaded, reach for `loadMissing()` rather than `load()`:

```php
// load() always fires the query, even if already loaded
$post->load('tags');

// loadMissing() skips the query if the relation is cached
$post->loadMissing('tags');

```

This matters inside service classes that can be called from both a controller (where `with()` was used) and a queued job (where it was not).

### Preventing Lazy Loading Globally in Development

Laravel ships with `Model::preventLazyLoading()`. Enable it in `AppServiceProvider` for non-production environments:

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

```

This throws a `LazyLoadingViolationException` the moment any relationship is lazy-loaded, turning silent performance bugs into loud, catchable errors during development and CI.

### Chunking and Cursor Iteration for Large Result Sets

When processing thousands of rows, `get()` loads everything into memory. Prefer `cursor()` for read-only iteration or `chunkById()` for write operations:

```php
// cursor() uses a PHP generator — one model in memory at a time
Post::with('author')->cursor()->each(function (Post $post) {
    // process
});

// chunkById() is safe when rows are deleted/updated mid-process
Post::chunkById(500, function ($posts) {
    $posts->each(fn ($p) => $p->update(['processed' => true]));
});

```

Note: `cursor()` does **not** support eager loading via `with()` — the generator fetches one row at a time from the PDO cursor, so relationships will lazy-load. For large sets with relationships, `chunkById` + `loadMissing` is the correct pattern.

Key Takeaways
-------------

- Use `Model::preventLazyLoading()` in development to surface N+1 bugs immediately.
- Subquery selects replace eager-loaded aggregates with a single efficient query.
- Prefer `loadMissing()` over `load()` in reusable service methods.
- `cursor()` saves memory but does not support eager loading — use `chunkById()` when you need both scale and relationships.
- Assert query counts in Pest tests to prevent regressions.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [eloquent](https://www.msaied.com/public/articles?search=eloquent)
- [performance](https://www.msaied.com/public/articles?search=performance)
- [database](https://www.msaied.com/public/articles?search=database)
- [optimization](https://www.msaied.com/public/articles?search=optimization)

 Frequently asked questions 
---------------------------

  Does `with()` always prevent N+1 queries for nested relationships?Only if you specify the full dot-notation path, e.g. `with('author.profile')`. Specifying just `with('author')` will still lazy-load `author-&gt;profile` if you access it later.

   When should I use a subquery select instead of `withMax` or `withCount`?`withMax` and `withCount` are convenient but emit separate queries joined in PHP. A subquery select embeds the aggregate directly in the main SQL, which is often faster and avoids the extra round-trip, especially when you only need one aggregate column.

   Will `Model::preventLazyLoading()` break third-party packages?It can. Some packages lazy-load relationships internally. Limit the call to non-production environments and use `Model::handleLazyLoadingViolationUsing()` to log instead of throw if you need a softer rollout.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleSaga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues](https://www.msaied.com/public/articles/saga-lara-flow-durable-workflows-and-compensating-transactions-on-laravel-queues) [Next articleLaravel Pipeline Pattern: Building Custom Pipelines Beyond Middleware](https://www.msaied.com/public/articles/laravel-pipeline-pattern-building-custom-pipelines-beyond-middleware-3)  

   On this page
-------------

1. [The N+1 Problem Is Not Just a Beginner Mistake](#the-n1-problem-is-not-just-a-beginner-mistake)
2. [Reproducing the Classic Case](#reproducing-the-classic-case)
3. [Detecting Queries You Did Not Know Were There](#detecting-queries-you-did-not-know-were-there)
4. [Subquery Selects: Pulling Aggregates Without Extra Queries](#subquery-selects-pulling-aggregates-without-extra-queries)
5. [Lazy Eager Loading vs. load() vs. loadMissing()](#lazy-eager-loading-vs-codeloadcode-vs-codeloadmissingcode)
6. [Preventing Lazy Loading Globally in Development](#preventing-lazy-loading-globally-in-development)
7. [Chunking and Cursor Iteration for Large Result Sets](#chunking-and-cursor-iteration-for-large-result-sets)
8. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
