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

natcave's avatar
Level 10

Redis: Is there a way to retrieve an array of all cached items that have a key that start with a specific string?

Maybe I have the wrong idea, but let's say I have these keys in redis:

laravel:shopping_cart:1
laravel:shopping_cart:2
laravel:shopping_cart:3
laravel:shopping_cart:4
laravel:shopping_cart:5

Is there a simple way to iterate over any keys that start with "laravel:shopping_cart:" and return an array? Something like:

$shopping_carts = [
    1 => // laravel:shopping_cart:1 value,
    2 => // laravel:shopping_cart:2 value,
    3 => // laravel:shopping_cart:3 value,
    4 => // laravel:shopping_cart:4 value,
    5 => // laravel:shopping_cart:5 value,
]

I guess I could cheat and do a while loop starting from 0 and test every combination up to a point but that seems sloppy. I can't seem to find any info on retrieving existing values without first knowing the full key. Maybe I'm just missing it or perhaps is this where I get off the Redis train and head over to MYSQL?

Thanks for any insight!

0 likes
5 replies
natcave's avatar
Level 10

Thanks for your response @Cronix,

I think I passed by that page while hunting for an answer. I'm looking for a way to retrieve the data within the laravel app, not on the command line. Sorry for not being clear.

Do you know of a way to retrieve the data via the Cache or Redis facades perhaps? If you have a quick code example that would help. Thanks.

Cronix's avatar
Cronix
Best Answer
Level 67

Most redis packages implement the keys() function, or they have a way to execute raw commands without using the cli. I was just pointing you to the generic function that you'd be looking for. Which redis package are you using?

Like with phpredis you can:

$redis->keys('laravel:shopping_cart:*');
1 like
natcave's avatar
Level 10

Awesome! I found it.

I think I was thrown off because I was trying to access the data via cache (I'm using redis as my cache driver). It works when I start from redis.

Here's my solution:

$key_prefix = "laravel:shopping_cart:"; 
$shopping_carts = [];

foreach(Redis::keys("{$key_prefix}*") as $shopping_cart_key){
    $shopping_carts[substr($shopping_cart_key, strlen($key_prefix))] = unserialize(Redis::get($shopping_cart_key));
}

Thanks for your help @Cronix

2 likes
Cronix's avatar

No problem, please mark the correct answer as the solution.

Please or to participate in this conversation.