Remove cache keys by pattern/wildcard

13,448

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();
Share:
13,448

Related videos on Youtube

j3491
Author by

j3491

Updated on June 04, 2022

Comments

  • j3491
    j3491 almost 2 years

    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?

  • j3491
    j3491 about 7 years
    Thanks, I actually read about tags but didn't realize I could use it for dynamic tags with user ids. So I guess something like: Cache::tags(['user:123'])->remember('items', 60, function () {...?
  • mattyh88
    mattyh88 over 6 years
    Not supported when using 'file' or 'database' driver :(
  • iRaS
    iRaS over 4 years
    tags are a pain in the ass in every key value store. no matter what driver you use. a requested wildcard solution can be faster in most systems.
  • Kurucu
    Kurucu almost 4 years
    This isn't supported with DynamoDB on Vapor, either.