Eloquent Query Optimization: From 3s to 40ms
A real debugging session where we traced a slow admin page, eliminated N+1 queries, and reduced response time by 98%. Step by step.
Last week I was profiling one of our admin dashboards when I noticed something alarming: a single page load was triggering 847 database queries. The page took 3.2 seconds to load. Users were complaining.
Here's exactly how we fixed it.
Step 1: Enable Query Logging
DB::enableQueryLog();
// ... your code
dd(DB::getQueryLog());
This is your first step whenever something feels slow. The output is often shocking.
Step 2: Identify the N+1 Problem
Our dashboard was loading a list of servers, then for each server, it was loading the associated user, the associated plan, and the associated stats separately. Classic N+1.
The fix is always the same: eager loading.
// Before (N+1 hell)
$servers = Server::all();
// After (single query)
$servers = Server::with(['user', 'plan', 'latestStats'])->get();
Step 3: Add Strategic Indexes
After eliminating N+1, we added composite indexes on the most-queried columns. The combination of eager loading + proper indexing took us from 847 queries to 4 queries, and from 3.2 seconds to 40 milliseconds.
This is the kind of optimization that feels like magic until you understand why it works.