Back to Blog
Caching Strategies for Production Laravel Applications
Cache Everything Possible
Caching is the single most effective performance optimization. Every cache hit is a database query avoided, an API call skipped, or a computation saved.
Application Caching
// Cache expensive queries
$products = Cache::remember('popular_products', 3600, function () {
return Product::withCount('orders')
->orderByDesc('orders_count')
->limit(20)
->get();
});
// Cache tags for related invalidation
Cache::tags(['products'])->put('product_' . $id, $product, 3600);
Cache::tags(['products'])->flush();
Route and Config Caching
# On every deployment
php artisan config:cache
php artisan route:cache
php artisan view:cache
# Clear when developing
php artisan optimize:clear
OPcache
; php.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0 ; Disable in production
HTTP Caching
// Response caching headers
return response($content)
->header('Cache-Control', 'public, max-age=3600')
->header('ETag', md5($content));
// Middleware for cache headers
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->isMethod('GET') && $response->isSuccessful()) {
$response->setCache([
'public' => true,
'max_age' => 3600,
]);
}
return $response;
}
CDN for Static Assets
// config/filesystems.php
'asset_url' => env('ASSET_URL', 'https://cdn.example.com'),
// In views
Cache Invalidation Strategies
- Time-based: Cache expires after duration
- Event-based: Invalidate when data changes
- Tag-based: Invalidate related items together
Conclusion
Layer your caching: OPcache for PHP, Redis for application data, HTTP headers for browsers, CDN for assets. Cache aggressively, invalidate precisely.
Related Articles
Need Help With Your Project?
I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.
Get In Touch