Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world usage example of Laravel Cache Tags

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 ?

like image 257
Foued MOUSSI Avatar asked Oct 23 '25 21:10

Foued MOUSSI


1 Answers

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.

like image 182
Ersin Demirtas Avatar answered Oct 26 '25 23:10

Ersin Demirtas