laravelcachingredislaravel-12

How can I set Redis key prefixes for sessions, cache, and queues separately in Laravel 12 (PHP 8.4)?


We’re running a Laravel 12 application (PHP 8.4) using Redis for sessions, cache, and queues — all within a single Redis database.

'redis' => [
    'client' => 'phpredis',
    'options' => [
        'cluster' => env('REDIS_CLUSTER', 'redis'),
        'prefix' => env('REDIS_PREFIX', 'site_'),
    ],

    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

    'cache' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'database' => 0,
        'prefix' => 'site_cache_',
    ],

    'session' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'database' => 0,
        'prefix' => 'site_session_',
    ],

    'queue' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'database' => 0,
        'prefix' => 'site_queue_',
    ],
],

Our goal is to:

However:

What we’d like to confirm

  1. Is it safe and recommended to use the same Redis database for cache, sessions, and queues — as long as each has its own prefix or not?
  2. How can we correctly define separate prefixes for each system so that Laravel respects them?

Solution

  • In Laravel, you can give different Redis prefixes for sessions, cache, and queues by defining separate Redis connections in config/database.php, then linking each feature (session, cache, queue) to its own connection. This keeps their keys organized and prevents overlap.

    Here’s short working code:

    // config/database.php
    'redis' => [
      'cache' => ['database' => 1, 'prefix' => 'cache_'],
      'session' => ['database' => 2, 'prefix' => 'sess_'],
      'queue' => ['database' => 3, 'prefix' => 'queue_'],
    ];
    
    // config/cache.php
    'stores' => ['redis' => ['connection' => 'cache']];
    
    // config/session.php
    'connection' => 'session';
    
    // config/queue.php
    'connections' => ['redis' => ['connection' => 'queue']];