Is there a way in newer laravel versions to cache many things with a certain prefix and then get all by doing Cache::get(‘prefix_*) or something ?
I’m trying to cache the Online Users for like 5 minutes and I want the cache to expire for each user individually, unless the expiration is updated for it by using a middleware.
But the problem I have run into is that I can’t retrieve all users if I store them as individual Keys:
Cache::put('online_users_'.auth()->id(), auth()->user(), now()->addMinutes(5));
And I would like to get them by using something like :
Cache::get('online_users_'); or Cache::get('online_users_*');
I could try using tags for this problem , but as they are not even explained in the docs after laravel 10 , I was wondering if there is another way around this , that would allow for the individual keys to expire in their own and be individually stored.
Thanks.
2
Answers
I would appreciate a solution for the file driver ,but I managed the following using the REDIS driver ,to get all the keys and values based on the prefix online_user_*:
I also had to remove the prefix from database.php
Since your idea is to put all "online users" in the same cache, you can do it like this:
This essentially creates a
key:value
array inside youronline_users
cache.Now, when you try to get the records from the cache:
You would get data like this:
where 1 or 2 will be your
auth users ID
, andUserObject1
orUserObject2
will be an object that gets returned byauth()->user()
.You can then even get a specific user object from cache, like this: