
Laravel Guru
Caching is one of the most effective ways to improve application performance. Laravel provides multiple caching strategies to suit different needs.
Laravel supports multiple cache drivers:
# File-based caching CACHE_DRIVER=file # Redis (recommended for production) CACHE_DRIVER=redis # Memcached CACHE_DRIVER=memcached # Database CACHE_DRIVER=database
// Store data in cache Cache::put('key', 'value', 3600); // 1 hour // Retrieve from cache $value = Cache::get('key'); // Cache with default value $value = Cache::get('key', 'default'); // Remember pattern $users = Cache::remember('users.all', 3600, function () { return User::all(); });
class Post extends Model { public function getRouteKeyName() { return 'slug'; } public static function findBySlugCached($slug) { return Cache::remember("posts.{$slug}", 3600, function () use ($slug) { return static::where('slug', $slug)->first(); }); } }
// Cache expensive queries $popularPosts = Cache::remember('posts.popular', 1800, function () { return Post::with('author') ->where('views', '>', 1000) ->orderBy('views', 'desc') ->take(10) ->get(); });
// Store with tags Cache::tags(['posts', 'authors'])->put('post.1', $post, 3600); // Flush by tag Cache::tags(['posts'])->flush();
class Post extends Model { protected static function booted() { static::saved(function ($post) { Cache::forget("posts.{$post->slug}"); Cache::forget('posts.popular'); }); static::deleted(function ($post) { Cache::forget("posts.{$post->slug}"); }); } }
// In your controller public function show(Post $post) { return response($post) ->header('Cache-Control', 'public, max-age=3600') ->header('ETag', md5($post->updated_at)); }
// Artisan command to warm cache class WarmCache extends Command { protected $signature = 'cache:warm'; public function handle() { $this->info('Warming cache...'); // Warm popular queries Cache::remember('posts.popular', 3600, function () { return Post::popular()->get(); }); $this->info('Cache warmed successfully!'); } }
Proper caching can reduce response times from seconds to milliseconds!

Discover proven techniques to optimize your Laravel applications for better performance, including caching strategies and database optimization.

Essential security practices to protect your Laravel applications from common vulnerabilities and attacks.