laracoft's avatar

When and how Laravel prunes/expires/deletes its cache folder

Anyone knows when and how Laravel prunes it's storage\framework\cache folder? i.e. delete cache entries that have expired.

I'm trying to locate the code to understand their caching mechanism. Thank you.

0 likes
9 replies
jlrdw's avatar

Isn't it cleared if you give a time, i.e.,

Cache::put('key', 'value', now()->addMinutes(10));

Seems you could write an artisan command for other cache.

1 like
laracoft's avatar

@jlrdw

Not the code we write, rather, the code that the Laravel team wrote to delete files from inside the storage\framework\cache folder. I don't think they will let the folder grow forever.

  1. Let's say we run Cache::put('one-time-use-key', ...) and makes it valid for only 10 minutes
  2. Laravel creates a file in the cache folder
  3. 15 minutes later (or much later), how does Laravel remove the file? $scheduler?

My question is similar to, how does Linux delete/maintain the /var/log folder? Answer: logrotate, except here, I'm trying to track down Laravel framework's PHP code.

rodrigo.pedra's avatar
Level 56

Short answer: it doesn't.

At least not for the file driver. I also think that not for the database driver either.

Actually for the driver it works, the underlying engine takes care of it (such as DynamoDB, Memcached, etc.).

There is an Artisan command to clear all cached data, but not for pruning only expired data.

I guess the philosophy is that when you try to access an expired key it will refresh its content.

But that is a problem when one's app relies on dynamic generated cache keys that doesn't get hit after some time. For example caching blog posts using by their ids. If you use the file or database cache drivers, they will grow, and grow, and without pruning expired keys the disk space will still be used after expiration.

There are some packages that add this ability, one example that adds pruning for the file cache driver is:

https://github.com/arifhp86/laravel-clear-expired-cache-file

There are reports of issues due to lack of expired cache pruning, one from Laravel's issue tracker is:

https://github.com/laravel/framework/issues/28581

1 like
shamshadzaheer's avatar

You can do it this way.

$search_count = 0;

        // Books
        $books = Book::latest('id')
                    ->published()
                    ->when(request()->has('search'), function($query) {
                        $keyword = "%".request()->input('search')."%";
                        return $query->where('title', 'like', $keyword);
                    });

        // Update Search Count
        if (request()->has('search')) {
            $search_count = $books->count();
        }

        $books = $books->simplePaginate()
        ->appends(request()->all());

        // View
        return view('home', compact('books', 'search_count'));

Please or to participate in this conversation.