Skip to main content

Caching and Performance Optimization

26/28
Chapter 7 Testing and Production Deployment

Caching and Performance Optimization

20 min read Lesson 26 / 28

Making Your Application Fast

The Cache API

use Illuminate\Support\Facades\Cache;

// Remember pattern
$posts = Cache::remember('featured_posts', now()->addHour(), function () {
    return Post::with(['author', 'tags'])
        ->published()
        ->featured()
        ->latest()
        ->limit(6)
        ->get();
});

// Manual operations
Cache::put('key', $value, now()->addMinutes(60));
Cache::forget('featured_posts');
Cache::flush(); // Clear everything

Invalidation via Observers

class PostObserver
{
    public function saved(Post $post): void
    {
        Cache::forget('featured_posts');
        Cache::forget("post_{$post->slug}");
    }
}

Laravel Optimization Commands

php artisan optimize        # Cache config, routes, views
php artisan optimize:clear  # Clear all caches (development)

Database Optimization

// Always eager load
$posts = Post::with(['author', 'category', 'tags'])->get();

// Prevent lazy loading in development
Model::preventLazyLoading(! app()->isProduction());

// Use database indexes
$table->index(['is_published', 'published_at']);

OPcache

Enable in php.ini for production:

opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000