Eloquent N+1: detection in production, not just development
Model::preventLazyLoading() throws exceptions in development, which is great. But we have N+1 issues that only appear with production data volumes.
How do people catch these before they affect users?
Clockwork or Laravel Debugbar in staging captures per-request query counts. Set a threshold alert: if any request makes more than 20 queries, flag it. Catches most N+1 issues without full profiling.
Telescope in staging with the query watcher shows slow queries and their duplicates. Group by query pattern to spot N+1: if the same parameterized query runs 50 times on one request, that is the bug.
The query log listener approach: before controller dispatch, count queries. After dispatch, check the count. If above threshold, log with the request path and query list. In production with a high threshold (100) this catches major regressions without much overhead.
Static analysis with Larastan (Laravel PHPStan rules) can catch some N+1 patterns when the relation is accessed in a loop without eager loading. Not 100% but better than nothing in CI.
Scaling often reveals N+1 that staging misses because staging has 100 records and production has 100k. The loop executes 100k times instead of 100 and suddenly the page takes 20 seconds. The only reliable way is load testing with production data volumes.
We added ->with() calls based on Telescope flagging, but then found new N+1 in the new data after. It was a whack-a-mole problem until we added a query count assertion to our integration tests for every endpoint.
```php blocks are runnable.