PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 3, 2022

[FIXED] How to get list of all cached items by key in Laravel 5?

 February 03, 2022     caching, key, laravel, laravel-5, php     No comments   

Issue

The Cache class in laravel has methods such as get('itemKey') to retrieve items from the cache, and remember('itemKey', ['myData1', 'myData2']) to save items in the cache.

There is also a method to check if an item exists in the cache: Cache::has('myKey');

Is there any way, (when using the file-based cache driver), to get a list of all items in the cache?

For instance, something that might be named something like "Cache::all()" that would return:

[
    'itemKey' => [
        'myData1',
        'myData2'
   ],
   'myKey' => 'foo'
]

The only way I can think of doing this is to loop through all possible key names using the Cache::has() method. i.e. aaa, aab, aac, aad... but of course, this is not a solution.

I can't see anything in the documentation or the API that describes a function like this, but I don't think its unreasonable to believe that one must exist.


Solution

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));
  }
}


Answered By - jedrzej.kurylo
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing