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/01M22N44A70A5MC2S599JP0MPH.webp)  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) 

 [ ![Livewire v4.4.6 Released: Bug Fixes, Test Improvements, and Alpine v3.17.4](https://cdn.msaied.com/689/454c52282f3ef5d585905e5952ca969c.png) Livewire Laravel Alpine.js 

### Livewire v4.4.6 Released: Bug Fixes, Test Improvements, and Alpine v3.17.4

Livewire v4.4.6 ships with 18 changes including validation performance improvements, better test assertions, k...

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

 21 Sep 2026     3 min read  

  Read    

 ](https://msaied.com/articles/livewire-v446-released-bug-fixes-test-improvements-and-alpine-v3174) [ ![Laravel 14: New Features, Breaking Changes, and PHP 8.4 Requirement](https://cdn.msaied.com/688/2dfe8f11b0bef35c0ee6db912004209f.png) Laravel 14 PHP 8.4 Breaking Changes 

### Laravel 14: New Features, Breaking Changes, and PHP 8.4 Requirement

Laravel 14 is expected in Q1 2027 and will require PHP 8.4. Here is everything known so far from the master br...

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

 21 Sep 2026     4 min read  

  Read    

 ](https://msaied.com/articles/laravel-14-new-features-breaking-changes-and-php-84-requirement) [ ![Building a Laravel Package: Service Providers, Auto-Discovery, and Config Merging](https://cdn.msaied.com/687/e53f819c8f897c1ad12a1df0661a18f7.png) laravel packages service-providers 

### Building a Laravel Package: Service Providers, Auto-Discovery, and Config Merging

Learn how to build a production-ready Laravel package from scratch — covering service provider design, auto-di...

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

 21 Sep 2026     1 min read  

  Read    

 ](https://msaied.com/articles/building-a-laravel-package-service-providers-auto-discovery-and-config-merging-4) 

   [  ![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)
