Eloquent N+1 Optimization for Laravel Developers | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Eloquent Query Optimization: Slaying N+1 Problems at Scale        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)

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

  #laravel   #eloquent   #performance   #database   #optimization  

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

     8 Aug 2026      4 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

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

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Feloquent-query-optimization-slaying-n1-problems-at-scale&text=Eloquent+Query+Optimization%3A+Slaying+N%2B1+Problems+at+Scale) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Feloquent-query-optimization-slaying-n1-problems-at-scale) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  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. 

      Q02  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. 

      Q03  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. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues](https://cdn.msaied.com/520/d77bd3c0cecb6fb89c16f85648e7e369.png) Laravel Workflows Saga Pattern 

### Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues

Saga Lara Flow is a Laravel package that lets you write long-running business processes as plain PHP methods o...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 7 Aug 2026     4 min read  

  Read    

 ](https://msaied.com/articles/saga-lara-flow-durable-workflows-and-compensating-transactions-on-laravel-queues) [ ![Filament v4.12 & v5.7: Major Performance Improvements and Security Patches](https://cdn.msaied.com/518/48e5a4da1b38d6cf27a0117baa547e1b.png) Filament Laravel Performance 

### Filament v4.12 &amp; v5.7: Major Performance Improvements and Security Patches

Filament v4.12.6 and v5.7.6 ship massive rendering speed gains—up to 92% faster form fields—alongside security...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 6 Aug 2026     1 min read  

  Read    

 ](https://msaied.com/articles/filament-v412-v57-major-performance-improvements-and-security-patches) [ ![Managed Queues: Autoscaling Queue Workers on Laravel Cloud](https://cdn.msaied.com/519/854099015015dbc72dd8743202b69efc.png) Laravel Cloud Queue Workers Autoscaling 

### Managed Queues: Autoscaling Queue Workers on Laravel Cloud

Laravel Cloud's managed queues feature autoscales workers based on queue pressure, surfaces failed jobs in a r...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 6 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/managed-queues-autoscaling-queue-workers-on-laravel-cloud) 

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

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
