Teaching
Fixing N+1 queries one by one is the wrong strategy. Prevent lazy loading entire...
You fixed the N+1. Telescope confirmed it. Then production slows down two weeks later. Here is what happened.
You fixed the N+1. Telescope confirmed it. Then production slows down two weeks later.
Here is what happened.
Here is what happened.
Eager loading fixes the path you tested.
Eager loading fixes the path you tested. It does not fix the model. Somewhere else in the codebase — a different controller, a queued job, a Nova resource — the same relation gets accessed without a load, and Laravel happily fires a query per row. You never saw it because your test path was clean.
The real problem is that lazy loading is on by default.
The real problem is that lazy loading is on by default. Every relation on every model is a loaded gun. You are one `foreach` away from 200 queries.
The durable fix is one line in `AppServiceProvider`:
The durable fix is one line in `AppServiceProvider`:
`Model::preventLazyLoading(!app()->isProduction());`
`Model::preventLazyLoading(!app()->isProduction());`
In local and staging, any lazy-loaded relation throws an exc...
In local and staging, any lazy-loaded relation throws an exception immediately. You cannot merge code that has the problem. By the time it reaches production, the gun is unloaded.
A few things to do alongside it:
A few things to do alongside it:
1.
1. Add `Model::preventLazyLoading(true)` in your CI test suite — not just local. 2. Run `php artisan telescope:clear` and replay your full user journey after enabling it. You will find relations you forgot existed. 3. When you do need a lazy load for a legitimate reason, use `$model->loadMissing('relation')` explicitly so the intent is visible in the code.
One caveat: if you are running Laravel older than 8.x, `prev...
One caveat: if you are running Laravel older than 8.x, `preventLazyLoading` is not available. In that case, Telescope's query count per request in staging is your next best signal — set a threshold and treat anything above it as a failing test.
How are you catching this in CI before it reaches production...
How are you catching this in CI before it reaches production?
The one-liner
Fixing N+1 queries one by one is the wrong strategy. Prevent lazy loading entirely.
Building something like this? Let us talk.
