Laravel Performance Optimization: Complete Guide
Introduction
Laravel performance optimization is essential for building fast, responsive applications. This guide covers everything from database query optimization to caching strategies and deployment best practices.
We'll explore techniques that can dramatically improve your application's response times and handle increased traffic loads.
Query Optimization
Efficient database queries are the foundation of Laravel performance.
Eager Loading
// N+1 Query Problem
$posts = Post::all(); // Loads posts
foreach ($posts as $post) {
echo $post->author->name; // Additional query for each post
}
// Solution: Eager Loading
$posts = Post::with('author')->get();
// Nested Eager Loading
$posts = Post::with(['author', 'comments', 'comments.user'])->get();
Select Only Required Columns
// Bad: Selects all columns
$users = User::where('active', 1)->get();
// Good: Selects only needed columns
$users = User::where('active', 1)
->select('id', 'name', 'email')
->get();
Chunking Large Datasets
// Process large datasets in chunks
User::where('active', 1)
->chunk(100, function ($users) {
foreach ($users as $user) {
// Process each user
$this->processUser($user);
}
});
Where Clauses Optimization
// Use whereIn for multiple OR conditions
// Bad
$users = User::where('role', 'admin')
->orWhere('role', 'editor')
->orWhere('role', 'author')
->get();
// Good
$users = User::whereIn('role', ['admin', 'editor', 'author'])->get();
Caching Strategies
Laravel provides multiple caching options to reduce database load.
Route Caching
// Cache routes for faster lookup
php artisan route:cache
// Clear route cache
php artisan route:clear
Configuration Caching
// Cache configuration
php artisan config:cache
// Clear configuration cache
php artisan config:clear
View Caching
// Laravel automatically caches views in production
// Ensure APP_ENV=production in .env
Application-Level Caching
// Store data in cache
Cache::put('user_'.$userId, $userData, 3600);
// Retrieve cached data
$user = Cache::get('user_'.$userId);
// Remember pattern - cache or compute
$users = Cache::remember('all_users', 3600, function () {
return User::all();
});
Database Indexing
Proper indexing dramatically improves query performance.
Creating Indexes
// Using migrations
Schema::table('orders', function (Blueprint $table) {
// Single column index
$table->index('customer_id');
// Composite index
$table->index(['customer_id', 'created_at']);
// Unique index
$table->unique('order_number');
// Full-text index (MySQL)
$table->fullText('description');
});
Query Builder Index Hints
// Force index usage
$orders = DB::table('orders')
->useIndex('idx_customer_date')
->where('customer_id', $customerId)
->get();
Queue Processing
Offload time-consuming tasks to queues for better response times.
Dispatching Jobs
// Dispatch a job
ProcessOrderJob::dispatch($order);
// Delayed dispatch
SendEmailJob::dispatch($user)->delay(now()->addMinutes(10));
// Chain jobs
ProcessOrderJob::dispatch($order)
->chain([
new SendOrderConfirmation($order),
new UpdateInventory($order),
new NotifyShipping($order)
]);
Queue Configuration
// config/queue.php
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
'block_for' => null,
],
],
OPcode Caching
OPcode caching improves PHP performance by caching compiled PHP code.
Installing OPcache
// php.ini configuration
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
Preloading
// config/preload.php
$files = require 'vendor/composer/autoload_classmap.php';
foreach ($files as $file) {
if (strpos($file, __DIR__) === 0) {
require_once $file;
}
}
Deployment Optimization
Optimize your Laravel application for production.
Composer Optimization
// Install with optimizations
composer install --optimize-autoloader --no-dev
// Dump optimized autoloader
composer dump-autoload --optimize
Production Checklist
# .env production settings
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com
# Enable queue worker
php artisan queue:work --daemon
# Schedule workers
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
HTTP/2 and HTTPS
// Ensure HTTPS is enforced
// App/Providers/AppServiceProvider.php
public function boot()
{
\URL::forceScheme('https');
}
Summary
Laravel performance optimization involves multiple layers: database queries, caching, indexing, queue processing, and deployment practices. Implementing these techniques will significantly improve your application's speed and scalability.
For more Laravel tutorials, check out Laravel Cache Optimization and Laravel Queues & Jobs Processing.