How to get list of all cached items by key in Laravel 5?
Older answers didn't work for me in Laravel 5.2 so I used this solution:
$storage = \Cache::getStore(); // will return instance of FileStore
$filesystem = $storage->getFilesystem(); // will return instance of Filesystem
$dir = (\Cache::getDirectory());
$keys = [];
foreach ($filesystem->allFiles($dir) as $file1) {
if (is_dir($file1->getPath())) {
foreach ($filesystem->allFiles($file1->getPath()) as $file2) {
$keys = array_merge($keys, [$file2->getRealpath() => unserialize(substr(\File::get($file2->getRealpath()), 10))]);
}
}
else {
}
}
There is no way to do that using Cache facade. Its interface represents the functionality that all underlying storages offer and some of the stores do not allow listing all keys.
If you're using the FileCache, you could try to achieve that by interacting with the underlying storage directly. It doesn't offer the method you need, so you'll need to iterate through the cache directory. It won't be too efficient due to a lot of disk I/O that might need to happen.
In order to access the storage, you need to do
$storage = Cache::getStore(); // will return instance of FileStore
$filesystem = $storage->getFilesystem(); // will return instance of Filesystem
$keys = [];
foreach ($filesystem->allFiles('') as $file1) {
foreach ($filesystem->allFiles($file1) as $file2) {
$keys = array_merge($keys, $filesystem->allFiles($file1 . '/' . $file2));
}
}