phplaravelcachingredislaravel-10

How to get all cached keys with certain prefix from the Cache in Laravel?


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.


Solution

  • I manage to get this working with the File driver!

    By storing everyting inside of one key active_users and not using the ttl field of the put() method itself. But by keeping track of an expires_at field of my own inside the array.

    Inside the middleware class I do something like this:

        $activeForMinutes = 5;
        $sessionId = session()->getId();
        $cachedActiveUsers = Cache::get('active_users') ?? [];
    
        // Remove expired sessions.
        foreach ($cachedActiveUsers as $key => $cachedActiveUser) {
            if (!$cachedActiveUser['expires_at']->isFuture()) {
                unset($cachedActiveUsers[$key]);
            }
        }
    
        $userData = [
            'session'    => $sessionId,
            'name'       => $this->getUserName(),
             // etc..
        ];
    
        // Add new data.
        $cachedActiveUsers[$sessionId] = $userData;
        Cache::put('active_users', $cachedActiveUsers);
    

    And in the controller I can simply do this:

    $activeUsers = Cache::get('active_users');
    

    Hope this helps!