Lesson 4 of 9 · 25m
Eloquent Performance: N+1s, Indexes, and Memory
How ORM convenience turns into production load, and the eager loading, indexing, and batching techniques that keep Eloquent fast.
Most Laravel performance incidents are not exotic. They are a list endpoint issuing 2,001 queries, a report loading half the users table into memory, or a missing index that nobody noticed until the table reached ten million rows. Eloquent is productive because it hides SQL; production work requires knowing exactly when to look underneath it.
The N+1 query is the classic failure
// 1 query for orders, then 1 query per order for customer
$orders = Order::latest()->take(50)->get();
foreach ($orders as $order) {
echo $order->customer->name;
}Fix it by eager loading:
$orders = Order::with('customer:id,name')->latest()->take(50)->get();Select only the columns the consumer needs. select * across a wide table is not free, especially when rows contain large JSON or text columns. For nested relations, use constrained eager loading instead of loading full relation graphs:
User::with(['orders' => fn ($q) => $q->where('status', 'open')->latest()->take(5)])->get();Indexes are part of the application, not the DBA's problem
Schema::table('orders', function (Blueprint $table) {
$table->index(['customer_id', 'status', 'created_at'], 'orders_customer_status_created_index');
});Match the index to the query's filters and ordering. An index on status alone may be useless when almost every row is active; the composite index above supports both the customer filter and the sort. Use EXPLAIN on production-like data. A query that uses an index in development can scan the table in production because the row distribution is different.
Batch large datasets
Order::where('status', 'open')
->orderBy('id')
->chunkById(500, function ($orders) {
foreach ($orders as $order) {
// process one row; do not accumulate them all
}
});chunk() uses offsets and gets slower as the offset grows. chunkById() pages by indexed primary key. cursor() is memory-efficient for reads but still processes one row at a time and can hold database resources open; use it deliberately.
Watch transaction shape under concurrency
Transactions should be short. Do not send mail, call Stripe, or resize images inside one. If you update balance-like data, use row locking deliberately:
DB::transaction(function () use ($accountId) {
$account = Account::whereKey($accountId)->lockForUpdate()->firstOrFail();
$account->decrement('balance', 100);
});lockForUpdate serializes competing writes to the same row. That is correctness, not a performance flaw; the performance flaw is holding the lock while doing unrelated slow work.
Field notes
- Turn on strict mode locally:
Model::preventLazyLoading(! app()->isProduction())catches N+1s before review does. DB::listen()or Laravel Telescope can show query counts, but never ship Telescope enabled publicly in production.- Pagination with
paginate()runs a count query. Huge tables sometimes need cursor pagination instead. - Do not cache a query whose underlying invalidation rule you cannot explain. Stale correctness bugs cost more than slow queries.
Was this lesson helpful?