Laravel Mastery: Performance Optimisation

11 minute read Laravel Mastery · Part 6

Optimise your Laravel app with advanced strategies including query tuning, caching layers, queue configuration, and runtime profiling tools.

Performance is more than just page speed - it’s about efficient memory usage, minimal queries, and scalable throughput under load. Laravel offers powerful tools for every layer of optimisation.

Quick Wins First

Before going deep, ensure:

  • Caching is enabled (config:cache, route:cache, view:cache)
  • Queues are used for emails and slow jobs
  • Eager loading prevents N+1 queries

Query Optimisation

Use Laravel Debugbar or Telescope to inspect queries:

// Inefficient
$users = User::all();
foreach ($users as $user) {
    echo $user->profile->bio;
}

// Better
$users = User::with('profile')->get();

Optimise indexes:

CREATE INDEX idx_user_email ON users(email);

Use subqueries where needed:

$latestOrders = User::addSelect(['last_order_date' => Order::select('created_at')
    ->whereColumn('user_id', 'users.id')
    ->latest()
    ->limit(1)]);

Caching Layers

Use:

  • config:cache for performance
  • view:cache to precompile Blade
  • response()->cache() via middleware
  • Redis for database result and object caching
$users = Cache::remember('users.active', 3600, function () {
    return User::where('active', 1)->get();
});

Queue Optimisation

Use Supervisor to scale workers:

php artisan queue:work --tries=3 --timeout=90

Tune per connection (e.g. redis) in config/queue.php. Separate fast and slow queues:

Queue::pushOn('emails', new SendNewsletter);
Queue::pushOn('reports', new GenerateReport);

Monitor with Laravel Horizon for queue management.

Profiling & Monitoring

Use tools like:

  • Telescope – logs requests, queries, jobs
  • Debugbar – inline performance metrics
  • Clockwork – integrates with your browser
  • Blackfire / Xdebug – for deep PHP profiling

Example: identify memory leaks with Telescope or query bottlenecks with Debugbar.

Asset & Response Optimisation

  • Minify CSS/JS via Laravel Mix or Vite
  • Use lazy loading for images and components
  • Add gzip/brotli via server config (Nginx)
  • Set cache headers with middleware:
$response->header('Cache-Control', 'max-age=3600, public');

Real-World Results

In the Jeweller ecommerce project:

  • Load times dropped from 8s to 2s
  • Redis caching reduced DB load by 60%
  • Horizon helped isolate slow jobs
  • Static asset optimisation improved TTFB by 35%

Best Practices

  • Optimise first query, not just frontend
  • Use queues for anything over ~200ms
  • Profile memory usage under real load
  • Watch out for caching invalidation
  • Use indexing and pagination consistently