Step 1: Install Redis
composer require predis/predis
# or
pecl install redis
Step 2: Configure .env
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Basic Caching
use Illuminate\Support\Facades\Cache;
// Store value
Cache::put('key', 'value', now()->addMinutes(10));
// Get value
$value = Cache::get('key', 'default');
// Remember pattern (most common)
$users = Cache::remember('users', 3600, function () {
return User::all();
});
// Forever cache
Cache::forever('settings', $settings);
// Delete
Cache::forget('key');
Cache Tags
// Store with tags
Cache::tags(['users', 'profiles'])->put('user.1', $user, 3600);
// Get with tags
$user = Cache::tags(['users', 'profiles'])->get('user.1');
// Flush by tag
Cache::tags(['users'])->flush();
Model Caching Pattern
class Post extends Model
{
public static function getCached($id)
{
return Cache::tags(['posts'])->remember(
"post.{$id}",
3600,
fn() => static::with('author')->find($id)
);
}
protected static function booted()
{
static::saved(function ($post) {
Cache::tags(['posts'])->forget("post.{$post->id}");
});
static::deleted(function ($post) {
Cache::tags(['posts'])->forget("post.{$post->id}");
});
}
}
Cache Middleware
// Cache entire response
Route::get('/posts', [PostController::class, 'index'])
->middleware('cache.headers:public;max_age=3600');
Atomic Locks
$lock = Cache::lock('processing', 10);
if ($lock->get()) {
// Process...
$lock->release();
}
Monitor Cache
# Check memory usage
redis-cli INFO memory
# Monitor commands
redis-cli MONITOR
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!