Performance optimization separates good applications from great ones. Laravel 9 provides numerous optimization opportunities. At ZIRA Software, these techniques reduced response times by 60% across client applications.
Configuration Caching
# Cache configuration files
php artisan config:cache
# Cache routes
php artisan route:cache
# Cache views
php artisan view:cache
# Cache events
php artisan event:cache
# All optimizations
php artisan optimize
# Clear all caches
php artisan optimize:clear
Autoloader Optimization
# Production autoloader optimization
composer install --optimize-autoloader --no-dev
# Or dump optimized autoloader
composer dump-autoload --optimize --classmap-authoritative
Query Optimization
// Eager loading to prevent N+1
$posts = Post::with(['author', 'comments.user'])->get();
// Select only needed columns
$users = User::select('id', 'name', 'email')->get();
// Use chunking for large datasets
User::chunk(1000, function ($users) {
foreach ($users as $user) {
// Process user
}
});
// Lazy collections for memory efficiency
User::lazy()->each(function ($user) {
// Process without loading all into memory
});
// Use cursor for read-only operations
foreach (User::cursor() as $user) {
// Very memory efficient
}
Database Indexing
// Migration with proper indexes
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('slug')->unique();
$table->string('status');
$table->timestamp('published_at')->nullable();
$table->timestamps();
// Composite index for common queries
$table->index(['status', 'published_at']);
$table->index(['user_id', 'created_at']);
});
// Add index to existing table
Schema::table('orders', function (Blueprint $table) {
$table->index('customer_email');
});
Caching Strategies
// Cache expensive queries
$stats = Cache::remember('dashboard:stats', 3600, function () {
return [
'users' => User::count(),
'orders' => Order::sum('total'),
'products' => Product::where('active', true)->count(),
];
});
// Cache tags for easy invalidation
Cache::tags(['users', 'profile'])->put("user:{$id}", $user, 3600);
Cache::tags(['users'])->flush(); // Clear all user caches
// Model caching
class Post extends Model
{
protected static function booted()
{
static::saved(function ($post) {
Cache::forget("post:{$post->slug}");
Cache::tags(['posts'])->flush();
});
}
}
// Query result caching
$popularPosts = Cache::remember('posts:popular', 1800, function () {
return Post::withCount('views')
->orderByDesc('views_count')
->take(10)
->get();
});
Queue Heavy Operations
// Dispatch to queue instead of blocking
class OrderController extends Controller
{
public function store(Request $request)
{
$order = Order::create($request->validated());
// Queue these operations
SendOrderConfirmation::dispatch($order);
UpdateInventory::dispatch($order);
NotifyWarehouse::dispatch($order);
return response()->json($order);
}
}
// Use job batching for related operations
Bus::batch([
new ProcessImages($product),
new GenerateThumbnails($product),
new UpdateSearchIndex($product),
])->dispatch();
Response Optimization
// Compress responses
// In .htaccess or nginx config
// Enable gzip compression
// Use resource collections efficiently
class PostCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection,
'meta' => [
'total' => $this->total(),
],
];
}
}
// Pagination for large datasets
$posts = Post::paginate(20);
// API pagination with cursor for better performance
$posts = Post::cursorPaginate(20);
Asset Optimization
// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
],
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'axios'],
},
},
},
},
});
Deployment Checklist
#!/bin/bash
# deploy.sh
# Maintenance mode
php artisan down
# Update code
git pull origin main
# Install dependencies
composer install --optimize-autoloader --no-dev
# Run migrations
php artisan migrate --force
# Clear and rebuild caches
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
# Build assets
npm ci && npm run build
# Restart queue workers
php artisan queue:restart
# Exit maintenance mode
php artisan up
OPcache Configuration
; php.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
opcache.revalidate_freq=0
opcache.save_comments=1
opcache.jit=1255
opcache.jit_buffer_size=128M
Monitoring Performance
// Log slow queries
// In AppServiceProvider
DB::listen(function ($query) {
if ($query->time > 100) {
Log::warning('Slow query detected', [
'sql' => $query->sql,
'time' => $query->time,
'bindings' => $query->bindings,
]);
}
});
// Use Laravel Telescope in development
// Use Laravel Horizon for queue monitoring
Conclusion
Laravel 9 performance optimization combines caching, query optimization, and proper deployment strategies. Regular profiling and monitoring ensure applications stay fast at scale.
Need performance optimization? Contact ZIRA Software for Laravel performance consulting.