Eloquent N+1 Elimination &amp; Eager Loading at Scale | 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 N+1 Elimination: Eager Loading Strategies and Query Deduplication at Scale

 Eloquent N+1 Elimination: Eager Loading Strategies and Query Deduplication at Scale
====================================================================================

 N+1 queries silently destroy Laravel app performance. This guide covers eager loading strategies, query deduplication with load-once guards, and Eloquent relationship tricks that matter at production scale.

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

ShareCopy linkCopied

 ![Eloquent N+1 Elimination: Eager Loading Strategies and Query Deduplication at Scale](https://cdn.msaied.com/636/87a71d1826f8c6cce958da8377a0bdb9.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. [How Eloquent's Relationship Cache Works](#how-eloquents-relationship-cache-works)
3. [Eager Loading: with() vs load() vs loadMissing()](#eager-loading-codewithcode-vs-codeloadcode-vs-codeloadmissingcode)
4. [Nested Eager Loading and Constraint Closures](#nested-eager-loading-and-constraint-closures)
5. [The withCount and withExists Shortcuts](#the-codewithcountcode-and-codewithexistscode-shortcuts)
6. [Detecting N+1 in CI with Telescope and preventLazyLoading()](#detecting-n1-in-ci-with-telescope-and-codepreventlazyloadingcode)
7. [Load-Once Guards in Service Classes](#load-once-guards-in-service-classes)
8. [Chunked Processing and Eager Loading](#chunked-processing-and-eager-loading)
9. [Takeaways](#takeaways)

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

Every Laravel developer learns about N+1 queries early. Yet in production codebases with layered services, Blade components, and Livewire, they creep back in — often invisibly. The fix is not just slapping `with()` everywhere. It requires understanding *when* Eloquent fires queries, how the relationship cache works, and where deduplication breaks down.

How Eloquent's Relationship Cache Works
---------------------------------------

When you call `$post->comments`, Eloquent checks `$this->relations` on the model. If the key exists (even as an empty collection), it returns the cached result. If not, it fires a query.

This means:

```php
$post->comments; // fires query, caches result
$post->comments; // returns cached collection — no query
$post->load('comments'); // re-queries and overwrites cache
$post->setRelation('comments', collect()); // manually set, prevents any query

```

Understanding this cache is the foundation of every optimization below.

Eager Loading: `with()` vs `load()` vs `loadMissing()`
------------------------------------------------------

`with()` is for query-time loading. `load()` re-queries unconditionally. `loadMissing()` is the underused hero — it only fires a query if the relation is not already cached.

```php
// Bad: always re-queries even if already loaded
$posts->each(fn($p) => $p->load('author'));

// Good: skips already-loaded relations
$posts->loadMissing('author');

```

In service classes that receive models from different call sites, `loadMissing()` is the safe default.

Nested Eager Loading and Constraint Closures
--------------------------------------------

Dot notation handles nesting, but constraints require closures:

```php
Post::with([
    'comments' => fn($q) => $q->where('approved', true)->latest()->limit(5),
    'comments.author:id,name,avatar',
])->get();

```

Note the column selection on `comments.author` — always select the foreign key (`id`) plus only what you need. Omitting the FK breaks the relation hydration silently.

The `withCount` and `withExists` Shortcuts
------------------------------------------

Avoid loading full collections just to count them:

```php
// Bad: loads all comments into memory to count
$post->comments->count();

// Good: single subquery, adds comments_count attribute
Post::withCount('comments')->get();

// Even cheaper when you only need a boolean
Post::withExists('comments')->get(); // adds comments_exists

```

`withExists` compiles to a correlated `EXISTS` subquery, which the query planner can short-circuit on the first matching row.

Detecting N+1 in CI with Telescope and `preventLazyLoading()`
-------------------------------------------------------------

Laravel ships a first-class guard:

```php
// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());

```

This throws a `LazyLoadingViolationException` the moment any unloaded relation is accessed outside production. Pair it with a Pest architecture test:

```php
it('does not lazy load in feature tests', function () {
    Model::preventLazyLoading();
    // run your feature test suite — any violation throws
});

```

For production observability, Telescope's query panel groups duplicate queries. If you see the same query repeated with different bindings, that is your N+1.

Load-Once Guards in Service Classes
-----------------------------------

When a service method is called from multiple entry points, guard against redundant loads:

```php
class PostEnricher
{
    public function enrich(Post $post): Post
    {
        $post->loadMissing(['author', 'tags', 'category']);

        // safe to access now — no extra queries if already loaded
        return $post;
    }
}

```

This pattern is especially valuable in Filament resource pages where the same model flows through multiple actions and infolist entries.

Chunked Processing and Eager Loading
------------------------------------

When iterating large datasets, `chunk()` with `with()` is correct; `cursor()` is not — cursor returns a lazy generator of individual models with no batch context, so every relation access fires a query.

```php
// Good: each chunk of 500 eager-loads relations in 2 queries
Post::with('author')->chunk(500, function ($posts) {
    $posts->each(fn($p) => ProcessPost::dispatch($p));
});

// Dangerous for relations: each model is hydrated alone
Post::cursor()->each(fn($p) => $p->author->name); // N+1

```

Use `cursor()` only when you need memory efficiency on flat, relation-free queries.

Takeaways
---------

- Use `loadMissing()` in services — it is the safe, idempotent alternative to `load()`.
- Always select the FK column when constraining nested eager loads.
- Prefer `withCount` / `withExists` over loading collections for aggregates.
- Enable `Model::preventLazyLoading()` in non-production environments and enforce it in CI.
- `chunk()` + `with()` is the correct pattern for large dataset iteration; `cursor()` is not relation-safe.
- Profile with Telescope query grouping before optimizing — measure first.

- [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 `loadMissing()` work on Eloquent collections as well as individual models?Yes. Calling `$collection-&gt;loadMissing('relation')` inspects each model in the collection, groups those missing the relation, and fires a single batched query for them — the same efficiency as `with()` at query time.

   Will `Model::preventLazyLoading()` break existing tests that don't eager-load?It will throw exceptions for any lazy-loaded relation access, which is the point. Treat each violation as a bug to fix by adding the appropriate `with()` or `loadMissing()` call. Start with it enabled only in feature tests, then expand coverage.

   When should I use `withAggregate()` instead of `withCount()`?`withCount()` is a convenience wrapper around `withAggregate()`. Use `withAggregate()` directly when you need `sum`, `avg`, `min`, or `max` on a related column — for example, `Post::withAggregate('comments', 'rating', 'avg')` adds a `comments\_avg\_rating` attribute.

   ![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 articleLaravel Job Middleware: Rate Limiting, Throttling, and Skipping Jobs Without Hacks](https://www.msaied.com/public/articles/laravel-job-middleware-rate-limiting-throttling-and-skipping-jobs-without-hacks) [Next articleThe Pipeline Pattern in Laravel: Building Custom Pipelines Beyond Middleware](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-building-custom-pipelines-beyond-middleware-2)  

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

1. [The N+1 Problem Is Not Just a Beginner Mistake](#the-n1-problem-is-not-just-a-beginner-mistake)
2. [How Eloquent's Relationship Cache Works](#how-eloquents-relationship-cache-works)
3. [Eager Loading: with() vs load() vs loadMissing()](#eager-loading-codewithcode-vs-codeloadcode-vs-codeloadmissingcode)
4. [Nested Eager Loading and Constraint Closures](#nested-eager-loading-and-constraint-closures)
5. [The withCount and withExists Shortcuts](#the-codewithcountcode-and-codewithexistscode-shortcuts)
6. [Detecting N+1 in CI with Telescope and preventLazyLoading()](#detecting-n1-in-ci-with-telescope-and-codepreventlazyloadingcode)
7. [Load-Once Guards in Service Classes](#load-once-guards-in-service-classes)
8. [Chunked Processing and Eager Loading](#chunked-processing-and-eager-loading)
9. [Takeaways](#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)
