Back to Blog
Introduction
When I first deployed a Laravel application for a UK-based client, their dashboard was taking 5+ seconds to load. After implementing the techniques in this guide, we got it down to 200ms. Here's how.
Database Optimization
1. Use Indexes Wisely
-- Add indexes for frequently queried columns
ALTER TABLE orders ADD INDEX idx_user_id (user_id);
ALTER TABLE orders ADD INDEX idx_created_at (created_at);
ALTER TABLE orders ADD INDEX idx_status (status);
2. Eager Loading to Prevent N+1
// Bad: N+1 query problem
$orders = Order::all();
foreach ($orders as $order) {
echo $order->user->name; // Triggers a query each time
}
// Good: Eager load relationships
$orders = Order::with('user')->get();
foreach ($orders as $order) {
echo $order->user->name; // No additional queries
}
3. Select Only What You Need
// Bad: Selects all columns
$users = User::all();
// Good: Select specific columns
$users = User::select('id', 'name', 'email')->get();
Caching Strategies
Route Caching
php artisan route:cache
php artisan config:cache
php artisan view:cache
Important: Clear caches after deployment: php artisan optimize:clear
Application Caching
// Cache expensive queries
$products = Cache::remember('featured-products', 3600, function () {
return Product::where('featured', true)->with('category')->get();
});
Deployment Best Practices
- Use Queue Workers for heavy tasks
- Implement Redis for session and cache storage
- Enable OPcache in PHP configuration
- Use CDNs for static assets
- Database Connection Pooling
Results
Conclusion
Performance optimization is an ongoing process. Start with database queries, implement caching, and always measure before and after changes. Your users (and Google) will thank you.