Real world usage example of Laravel Cache Tags

7.9k Views Asked by At

According to Laravel Documentation

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);

Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);

What are they useful for ?

3

There are 3 best solutions below

2
Ersin Demirtas On BEST ANSWER

Exactly what the documentation mentions. You can group your cache with tags so then when you need it to, you could clear them by groups. This really depends on your needs.

For example if you are caching products:

Cache::put('product_' . $product->id, $product, $minutes);

Lets assume that now you want to delete all the products from cache. You'll have to clear every cache key with the pattern product_{id} one by one, but if you tag them with a common key (products for example), you could clear all the products at once:

Cache::tags(['products'])->put('product_' . $product->id, $product, $minutes);

You can also use the artisan command to clear specific tags:

php artisan cache:clear --tags=products

or programmatically

Cache::tags('products')->flush();

Additional info when using cache tags you must make sure the caching driver you are using supports the cache tags. For example, if you are running your tests against SQLite, the cache tags won't work. But if you run with Redis it works. For basic tag usage, the tags work fine. If you are building a complex caching mechanism I don't recommend using it.

0
xelber On

In my opinion (opinion only), Laravel cache tags have limited real-world use. Tagging is there for you to sort of indicate what elements the cache consists of. For example, say you are storing a full page cache, which has 10 products, 2 category details, 5 specials etc. The idea is that when any of that changes, you should be able to invalidate the full page cache without knowing what other elements were used to create the full page cache. With Laravel, you cannot do that. You need to know all the tags (in the same order!), which you will never know when for example, a category is updated.

A better option is https://github.com/swayok/alternative-laravel-cache

0
Mike On

Example: you create cache items with keys like 'filter[color]:filter[size]:filter[category]', with tens of colors, sizes and categories. That is done in order to cache complicated heavy-load query results. And once you decide to clear them all. If they are tagged by the same tag 'cached-filter-quieries', you could make it with a snap of the fingers. If not, there would be no easy way to do it.