5

In Laravel, we can store cache with this:

Cache::put($dynamickey, 'value', $minutes);

But this will end up more and more cache files stored even after it is expired. If we try to clean it with php artisan cache:clear or Cache::flush();, it will wipe out all the cache including those that are still valid.

Is it possible to have auto clean up that will clear only expired cache? Thanks.

user1995781
  • 19,085
  • 45
  • 135
  • 236

2 Answers2

0
$value = Cache::remember('users', function()
{
    return DB::table('users')->get();
});

Does the work. It validate if cache with given key exists and returns its value. It it does not exist or expired then refresh given cache key with new value.

For Images cache I uses logic like:

  1. tore image md5($file); //where $file === full image path with image name
  2. Store image md5(file_get_contents($file)); //self explaining method :)
  3. Then

    if (Cache::has($cacheKey_name) && !Cache::has($cacheKey_content)) { Cache::forget($cacheKey_name); Cache::forget($cacheKey_content); }

It will check if image is cached and only content changed. If yes then remove old cache and cache new image (with new content). With this logic you will have always fresh image content (with overwritten images).

Or, you can always create artisan task and create Controller to check all cache data in storage directory, then create Cron Task.

user2709153
  • 325
  • 3
  • 6
0

you can create an function like this

function cache($key,$value,$min){

    (Cache::has($key))?Cache::put($key,$value,$min):Cache::add($key,$value,$min);


if(Cache::has('caches')){
    $cache=Cache::get('caches');
    $cache[time()+(60*$min)]=$key;
    Cache::forget('caches');
    Cache::rememberForever('caches',function() use($cache){
        return $cache;
    });
}else{
    $cache[time()+(60*$min)]=$key;
    Cache::rememberForever('caches',function() use($cache){
        return $cache;
    });
}
$cache=Cache::get('caches');
foreach($cache as $key=>$value)
{
    if($key<time())
    {
        Cache::forget($value);
        array_forget($cache, $key);
    }
}
Cache::forget('caches');
Cache::rememberForever('caches',function() use($cache){
    return $cache;
});}

and to remove this cache empty folders you can edit

vendor\laravel\framework\src\Illuminate\Cache\FileStore.php

on line 182 after this code

public function forget($key)
{
    $file = $this->path($key);

    if ($this->files->exists($file))
    {
        $this->files->delete($file);

add a function to remove all empty folders , like blow code

    public function forget($key)
{
    $file = $this->path($key);

    if ($this->files->exists($file))
    {
        $this->files->delete($file);
         RemoveEmptySubFolders($this->getDirectory());

to use this function you can see it Remove empty subfolders with PHP

Community
  • 1
  • 1