Introduction
Cache tags help you group related cached items so you can clear them all at once. This keeps your app fast and organized.
Jump into concepts and practice - no test required
Cache tags help you group related cached items so you can clear them all at once. This keeps your app fast and organized.
Cache::tags(['tag1', 'tag2'])->put('key', 'value', $seconds); $value = Cache::tags(['tag1'])->get('key'); Cache::tags(['tag1'])->flush();
Cache::tags(['users'])->put('user_1', $userData, 3600);
$user = Cache::tags(['users'])->get('user_1');
Cache::tags(['posts'])->flush();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.
<?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";
Cache tags work only with cache drivers that support tagging, like Redis or Memcached.
Using tags helps avoid clearing unrelated cached data.
Cache tags group cached items for easy management.
You can clear all items with a tag using flush().
Tags require a compatible cache driver.
cache tags in Laravel?tags() method accepts an array of tags before calling put().Cache::tags([...])->put(key, value, time).Cache::tags(['products'])->get('item_1'); after Cache::tags(['products'])->flush(); is called?Cache::tags(['products'])->put('item_1', 'Book', 600);
Cache::tags(['products'])->flush();
$value = Cache::tags(['products'])->get('item_1');
echo $value ?? 'Not found';flush() on a tag clears all cached items under that tag.get('item_1') returns null, so the null coalescing operator outputs 'Not found'.Cache::tags('sessions')->put('session_1', 'data', 120);
Cache::tags(['sessions'])->flush();tags() method requires an array of tags, not a string.