0
0
Laravelframework~5 mins

Cache tags in Laravel

Choose your learning style9 modes available
Introduction

Cache tags help you group related cached items so you can clear them all at once. This keeps your app fast and organized.

You want to clear all cached data related to a specific user after they update their profile.
You cache different types of data but want to clear only one type without affecting others.
You have a blog and want to clear all cached posts when a new post is published.
You want to manage cache for different sections of your app separately.
You want to avoid clearing the entire cache when only some data changes.
Syntax
Laravel
Cache::tags(['tag1', 'tag2'])->put('key', 'value', $seconds);
$value = Cache::tags(['tag1'])->get('key');
Cache::tags(['tag1'])->flush();
Use an array of tags to group cache items.
Flushing a tag removes all cache items with that tag.
Examples
Cache user data with the tag 'users' for 1 hour.
Laravel
Cache::tags(['users'])->put('user_1', $userData, 3600);
Retrieve cached user data by tag and key.
Laravel
$user = Cache::tags(['users'])->get('user_1');
Clear all cached items tagged with 'posts'.
Laravel
Cache::tags(['posts'])->flush();
Sample Program

This example caches a product with two tags: 'products' and 'electronics'. It retrieves and prints the product, then clears all cache tagged 'electronics'. After flushing, trying to get the product returns 'Not found' because the cache was cleared.

Laravel
<?php
use Illuminate\Support\Facades\Cache;

// Store cache with tags
Cache::tags(['products', 'electronics'])->put('product_123', 'Smartphone', 600);

// Retrieve cached item
$product = Cache::tags(['products'])->get('product_123');
echo $product . "\n";

// Clear all electronics products cache
Cache::tags(['electronics'])->flush();

// Try to get the product again after flush
$productAfterFlush = Cache::tags(['products'])->get('product_123', 'Not found');
echo $productAfterFlush . "\n";
OutputSuccess
Important Notes

Cache tags work only with cache drivers that support tagging, like Redis or Memcached.

Using tags helps avoid clearing unrelated cached data.

Summary

Cache tags group cached items for easy management.

You can clear all items with a tag using flush().

Tags require a compatible cache driver.