Writing Eloquent Queries That Do Not Fall Over
Eloquent is a joy to write and a trap to scale. The same expressive API that makes prototypes fast will quietly issue thousands of queries in production. Here is how to keep it fast.
The N+1 Problem
The most common performance bug in any ORM is the N+1 query: one query to load a list, then one more per item to load a relationship.
Eager Loading
Load relationships up front with `with()`. One query for the parents, one for the children, instead of one per row. For nested relationships, use dot notation to eager load down the tree.
Fail Loudly in Development
Call `Model::preventLazyLoading()` in your local and testing environments. Any accidental lazy load throws instead of silently degrading, so you catch N+1 bugs before they ship.
Working With Large Result Sets
Loading a million rows into memory will kill your process. Stream instead of materialise.
Chunking and Cursors
Use `chunkById()` to process large tables in batches, or `cursor()` to iterate lazily with a single buffered query. Both keep memory flat regardless of table size.
Select Only What You Need
Fetching every column of a wide table wastes bandwidth and memory. Constrain columns with `select()` and load relationship columns explicitly.
Aggregate in the Database
Counting or summing in PHP means loading every row. Push aggregates down with `withCount()`, `sum()`, and raw expressions so the database does the work.
Closing Thoughts
Elegant Eloquent and fast Eloquent are not opposites, but they are not automatic either. Eager load, stream large sets, and let the database aggregate. Do that and the ORM scales with you.