Delete cache keys by pattern / pattern

I am creating a REST API with Lumen and want to cache some routes using Redis. For example. for route / users / 123 / elements that I use:

$items = Cache::remember('users:123:items', 60, function () { // Get data from database and return }); 

When changes are made to user elements, I clear the cache as follows:

 Cache::forget('users:123:items'); 

So far so good. However, I also need to clear the cache that I implemented for the categories of routes / users / 123 and / users / 123 /, since they include a list of items. This means that I also need to run:

 Cache::forget('users:123'); Cache::forget('users:123:categories'); 

More caches may appear in the future, so I'm looking for a pattern / wildcard, for example:

 Cache::forget('users:123*'); 

Is there any way to account for this behavior in Lumen / Laravel?

+7
laravel lumen
source share
1 answer

You can use cache tags .

Cached tags allow you to mark related items in the cache, and then clear all cached values ​​that have been assigned this tag. You can access the tag cache by passing an ordered array of tag names. For example, allow access to the tag cache and put the value in the cache:

 Cache::tags(['people', 'artists'])->put('John', $john, $minutes); 

You can clear all items that are assigned a tag or list of tags. For example, this operator will delete all caches marked by both people and authors, or both. So, Anna and John will be removed from the cache:

 Cache::tags(['people', 'authors'])->flush(); 
+5
source share

All Articles