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

Pixelairport's avatar

Switch redis database for cache

I started with redis. I need to have a fast database and now i decided also to cache things in another redis database. I use redisinsight and saw, that i can switch between the databases by number. I now want to put key/values with cache() into redis database number 2. But how can i set up this? If i user redis method, i can call select like this:

redis()->select(2)

Now I'm looking for setup in cache. I tried this:

        'mycache' => [
            'driver' => 'redis',
            'connection' => 'cache'
            'lock_connection' => 1,
        ],
```

And it works for database 1. Key/Value is set in database one. But when I use 2 here id does not work. Does anybody have an idea?
0 likes
8 replies
Sinnbeck's avatar

Have you tried setting database?

'mycache1' => [
            'driver' => 'redis',
            'connection' => 'cache'
            'lock_connection' => 1,
           'database' => 1
        ],
'mycache2' => [
            'driver' => 'redis',
            'connection' => 'cache'
            'lock_connection' => 1,
           'database' => 2
        ], 
Pixelairport's avatar

@Sinnbeck I did it really simple:

cache()->store('mycache1')->put('homer', 'simpson', 20);
cache()->store('mycache2')->put('fred', 'feuerstein', 20);
```

I know that it also in the documentation with 'database'=>XX, but it does not work. Maybe i should switch and do it with redis() helper method. But I think it would be better to use with cache because of functions like remember.
Sinnbeck's avatar

@Pixelairport what do you get if you do

cache()->store('mycache1')->put('homer', 'simpson', 20);
cache()->store('mycache2')->put('homer', 'feuerstein', 20);

dd(cache()->store('mycache1')->get('homer'));
Pixelairport's avatar

It is written into database 1 not two...

This would work, but its not done with cache

Redis::select(2);
Redis::zadd('Homer::Points', 100, uniqid());
Pixelairport's avatar
Pixelairport
OP
Best Answer
Level 12

Thx @sinnbeck for your help. I found the problem. I placed the database key into config/cache.php, but i had to set it in config/database.php and then use db key i set in database.php as connection value in cache.php. Sorry ... i just started with that topic.

Please or to participate in this conversation.