Laravel Performance Optimization: From 5s to 200ms Load Time

A comprehensive guide to optimizing Laravel applications. Learn about database indexing, caching strategies, query optimization, and deployment best practices.

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

  1. Use Queue Workers for heavy tasks
  2. Implement Redis for session and cache storage
  3. Enable OPcache in PHP configuration
  4. Use CDNs for static assets
  5. Database Connection Pooling

Results

Metric Before After
Page Load 5.2s 0.2s
DB Queries 85 12
Memory Usage 256MB 48MB

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.