image

Eloquent Performance Beyond with() — Indexing, Memory & Read Replicas

18 Nov, 2026 Abdelrahman Etry

Every Laravel developer knows how to fix N+1 queries with User::with('posts'). Yet production dashboards still time out and queue workers still crash with Allowed memory size exhausted. Once eager loading is handled, real bottlenecks live in how much data MySQL scans, how many models PHP hydrates into RAM, and how read/write splitting behaves under load.


1. Stop Hydrating 40 Columns When You Need 3

Running User::with('profile')->get() executes SELECT *, pulling massive TEXT or JSON payload columns across the network and instantiating heavy Eloquent model objects for every row. Constrain columns explicitly:


$orders = Order::query()
    ->select(['id', 'customer_id', 'total_cents', 'status', 'created_at'])
    ->with(['customer:id,name,email'])
    ->where('status', 'pending')
    ->get();

2. Composite Indexes Follow the Leftmost Prefix Rule

Adding individual single-column indexes on tenant_id, status, and created_at rarely helps a query filtering by all three. Create a single composite index ordered from highest equality selectivity to range filter:$table->index(['tenant_id', 'status', 'created_at']);


3. Batch Processing Without Memory Spikes

Calling ->get() on 250,000 rows loads every Eloquent model into RAM simultaneously. Use chunkById(1000) (which uses keyset pagination WHERE id > last_id instead of slow OFFSET queries) or lazyById() to keep worker memory flat under 30MB regardless of table size.


4. Read-Replica Lag & sticky => true

When scaling MySQL with read replicas, a user might update their profile (sent to the Primary DB) and immediately redirect to a page that reads stale data from a Replica 200ms behind. Enabling 'sticky' => true in config/database.php forces Laravel to read from the Primary connection for the remainder of any request cycle that performed a write.