Laravel cache get all items with tag

13,167

Solution 1

I think you use it wrong. As first argument you pass key of cache, as second value and as third expire time in minutes.

If you want to cache some bans with reason, for example assume you have in PHP some group of users who spammed, you could use something like that:

$bans = [
   [
       'ip' => 'test ip',
       'reason' => "spam: test reason",
   ],
   [
       'ip' => 'test ip2 ',
       'reason' => "spam: test reason 2",
   ]

];

Cache::tags('bans')->put('spam', $bans, 100);

$spams = Cache::tags('bans')->get('spam');
foreach ($spams as $spam) {
    echo $spam['ip'].' '.$spam['reason']."<br />";
}

So here you put into cache the whole array and now you can access items using standard foreach loop.

Solution 2

The underlaying Cache Drive is not supported retrieve all caches of a certain tag.

If u really need this kind of feature, u should looking for Redis, using Redis' hash instead of Cache's tags.

Here is some example code:

// Delete hash table - `bans`
Redis::del('bans');
// Setting hash table filed
Redis::hSet('bans', 'ip1', 'spam: test reason');
Redis::hSet('bans', 'ip2', 'spam: test reason 2');
// Get all filed form hash table - `bans`
dd(Redis::hGetAll('bans'));

Debug output will be:

array:2 [▼
  "ip1" => "spam: test reason"
  "ip2" => "spam: test reason 2"
]

Solution 3

In 'yourKeyGoesHere' you can insert a string used as same as a like with a * or insert directly the exactly key.

$redis = Cache::getRedis();
$a_keys = $redis->keys("*yourKeyGoesHere*");
Share:
13,167
Matthijn
Author by

Matthijn

Updated on October 30, 2022

Comments

  • Matthijn
    Matthijn over 1 year

    In Laravel you can place items in the Cache with a tag like:

    Cache::tags('bans')->put($result->ip, $result->reason);
    

    But I can't seem to find a way to get all items with a certain tag. Is it possible to retrieve all items with a certain tag?

    Like:

    Cache::tags('bans')->all(); 
    

    Or something like that

  • Vigs
    Vigs almost 9 years
    Is there no way to do something like Cache::tags([$tag])->all();? I have a very specific use case where I need to be able to retrieve every item from the cache that has a specific tag.
  • Ryan
    Ryan about 7 years
    I want to do the same as the question asker. But I've never found docs about how to retrieve all caches of a certain tag. Does that mean that tags are only helpful for deleting multiple caches at once? In the example above, the tags seem useless. How is $spams = Cache::tags('bans')->get('spam'); different from $spams = Cache::get('spam');?
  • Mickael
    Mickael about 6 years
    While it may answer the problem, you should add an explanation with your answer. What was the problem ? How your answer is supposed to solve it ?
  • parse
    parse almost 3 years
    Not a production solution.
  • Kunal Rajput
    Kunal Rajput about 2 years
    what do you mean by not a production solution