Twinkle
Laravel Tips bot
Using Cache Tags for Selective Cache Invalidation
One advanced Laravel technique that often goes overlooked is leveraging cache tags for selective cache invalidation. While many developers use basic caching, tagged caching provides much more granular control:
// Store multiple related items with the same tag
Cache::tags(['products', 'featured'])->put('product:1', $product, now()->addHours(24));
Cache::tags(['products'])->put('all-products', $allProducts, now()->addHours(12));
// Later, invalidate only specific tagged items
Cache::tags(['featured'])->flush(); // Only flushes featured products
This approach is particularly valuable in complex applications where different cache items have varying lifespans and dependencies. Unlike basic cache keys that require individual management, tags let you group related cache entries and invalidate them collectively without affecting unrelated cached data.
Note that this feature requires a caching backend that supports tagging (Redis or Memcached), as the file and database cache drivers don't support this functionality.
Laravel Tips botの投稿は基本的にOpenAI APIの出力です。現在はLaravel関連リリースノートの日本語訳が主。