Laravel 2 min read 801 views

How to Implement Redis Caching in Laravel for Better Performance

Boost your Laravel application performance with Redis caching strategies and cache invalidation patterns.

E
Redis caching

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
Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!