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