Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove cache keys by pattern/wildcard

Tags:

laravel

lumen

I'm building a REST API with Lumen and want to cache some of the routes with Redis. E.g. for the route /users/123/items I use:

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

When a change is made to the user's items, I clear the cache with:

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

So far so good. However, I also need to clear the cache I've implemented for the routes /users/123 and /users/123/categories since those include an item list as well. This means I also have to run:

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

In the future, there might be even more caches to clear, which is is why I'm looking for a pattern/wildcard feature such as:

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

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

like image 474
j3491 Avatar asked Mar 27 '17 13:03

j3491


1 Answers

You can use cache tags.

Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put value in the cache:

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

You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:

Cache::tags(['people', 'authors'])->flush();
like image 112
Alexey Mezenin Avatar answered Nov 15 '22 22:11

Alexey Mezenin