Hailwood Hailwood - 4 months ago 26
PHP Question

Deleting from Laravel 4 cache using pattern for key?

For my package we make use of the Laravel cache,

Every cache key we create is prefixed, so we get

mypackage-config
,
mypackage-md5ofafilename
At times I need to flush all cache files that my package has created, the issue? I only know the pattern of the cache keys, I don't know the entire key!

So, I need a way to go
Cache::forget('mypackage-*')
or similar, is this possible?

If it was just for my system I know I am using the file cache, so I could manually unlink the files, but because it is a generic package I don't know what cache method the end user is using, I just know the interface (aka the Laravel cache interface).

Answer

Easy - use Cache::getMemory()

foreach (Cache::getMemory() as $cacheKey => $cacheValue)
{
    if (strpos($cacheKey, 'mypackage') !== false)
    {
        Cache::forget($cacheKey);
    }
}

p.s. dont ever unlink 'cache' files manually. Laravel cache keeps a record of all cache records in an array, so it will be expecting the file to be there, even if you 'unlink' it.