Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mikevrind's avatar

Redis sessions prefix

I'm currently using Redis for caching en sessions. But I noticed that both are stored under the same prefix. Can this behavior be changed? It's quite annoying to search for a cache key between all sessions.

I know I could use a separate database for the sessions. But in my opinion it's strange to store sessions under a 'cache' prefix.

0 likes
7 replies
rezserve's avatar

I'm having the same problem. Did you find any solution for that?

dsup's avatar

I found a solution, you can update the Illuminate\Session\CacheBasedSessionHandler read(), write() and destroy() methods to prefix the $sessionId variable with any string prefix you want.

robrogers3's avatar

easier solution (I think). Update the cache.php config file and set the prefix to ''.

let me know what you find out.

dsup's avatar

@robrogers3 The issue is not the prefix in cache.php, but rather that sessions stored in redis are impossible to filter without having a prefix themselves.

With my solution, the redis session keys look like "laravel:session:voMKMBN2zvC4OiqUbQyFDHZBfdO69ifJlYjmRE4U" and are easy to filter.

cyrossignol's avatar

In Laravel 5.3 and later, we can change the Redis session prefix by just adding a new cache store definition to config/cache.php:

'stores' => [
    ...
    'redis:session' => [
        'driver' => 'redis',
        'connection' => 'default',
        'prefix' => 'session', // ta-da
    ],
],

Then change the value of store to redis:session in config/session.php.

For Laravel 5.2 and below, we can set the prefix manually (in a service provider, for example):

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->make('session')->driver('redis')
            ->getCache()
            ->getStore()
            ->setPrefix('session');
    }
}

Remember that clearing the cache will erase all data in the same Redis database even when we use different prefixes. To avoid this, set a different database number for the cache connection, or store the cache data in a separate Redis server.

2 likes

Please or to participate in this conversation.