How I Optimized Database Queries by 90% in a Laravel Application
Source: Dev.to
Background
When I inherited a Laravel application that was struggling with performance, the user dashboards were loading related data such as orders, customers, and products very slowly. I used Laravel Debugbar to analyze the queries and discovered the classic N+1 problem.
Step 1: Eager Loading
// Before: N+1 queries
$orders = Order::all();
foreach ($orders as $order) {
echo $order->customer->name; // New query each time!
}
// After: Optimized
$orders = Order::with(['customer', 'items.product'])->get();
Step 2: Query Scoping
public function scopeWithFullDetails($query)
{
return $query->with([
'customer.priceList',
'items.product.category',
'payments',
]);
}
Step 3: Strategic Caching
$products = Cache::remember('products.catalog', 3600, function () {
return Product::with('category')->get();
});
Results
- Page load time: 3–5 seconds → under 500 ms
- Database queries: 100+ → under 10 per page
- Server load reduced significantly
- Better user experience
Key Takeaways
- Always profile before optimizing – don’t guess where the bottleneck is.
- Eager loading is your friend, but avoid over‑eager‑loading everything.
- Cache wisely – not everything needs real‑time data.
- Think in relationships – design queries around how data connects.
- Performance optimization isn’t magic; it’s systematic analysis and thoughtful solutions.