skip to Main Content

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


  1. Chosen as BEST ANSWER

    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_*:

     public function index()
        {
            $cursor = '0';
            $onlineUsers= [];
    
            do {
                [$cursor, $keys] = Redis::scan($cursor, 'MATCH', 'online_user_*');
    
                foreach ($keys as $key) {
                    $onlineUsers[$key] = Redis::get($key);
                }
            } while ($cursor !== '0');
    
            return view('view.name', [
               
                'onlineUsers' => $onlineUsers,
            ]);
        }
    

    I also had to remove the prefix from database.php

     // 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_') . '_database_'),
    

  2. Since your idea is to put all "online users" in the same cache, you can do it like this:

    Cache::put('online_users', [auth()->id() => auth()->user()], now()->addMinutes(5));
    

    This essentially creates a key:value array inside your online_users cache.

    Now, when you try to get the records from the cache:

    Cache::get('online_users');
    

    You would get data like this:

    [
        1 => UserObject2,
        2 => UserObject1
    ]
    

    where 1 or 2 will be your auth users ID, and UserObject1 or UserObject2 will be an object that gets returned by auth()->user().

    You can then even get a specific user object from cache, like this:

    Cache::get('online_users')[auth()->id];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search