Caching is essential for speeding up expensive data retrieval and processing in production applications. Laravel provides several caching drivers to facilitate this. Two such drivers that come out of the box are the file
and database
cache drivers. Occasionally, it is a good idea to clear the cache, as regularly removing expired items can prevent storage overload, especially if you create many temporary items with random keys.
In Laravel, you can clear the cache using Cache::flush()
or php artisan cache:clear
. However, when using these methods, all entries are removed from the cache, including the framework cache, which can potentially cause issues with file cache driver permissions if, let's say, cache items are created by the www-data
user, but /bootstrap/cache/*
is owned by another user. Laravel Cache Evict is a package developed by Vincent Wong that helps you remove only the expired items in your cache in a memory-efficient and (for database caches) non-blocking way.
You install this package using Composer:
composer require vectorial1024/laravel-cache-evict
To evict the default cache in your Laravel app, you run:
php artisan cache:evict
Optionally, you can specify the cache to clear:
php artisan cache:evict file
Learn more about this package, including how to define your custom eviction strategies and view the source code on GitHub.