How To Clear Laravel Cache
Efficiency is the backbone of any successful application, and Laravel, one of the most popular PHP frameworks, understands this principle well. In its pursuit of enhancing performance, Laravel uses caches as a strategic tool. These caches serve as repositories for crucial data elements within your application, ranging from views and routes to events and beyond.
In this Laravel Tips post, we are going to see how to clear each type of cache.
Clear Application Cache
To clear application cache, you can use the following artisan command:
php artisan config:clear
To clear a certain application cache entry, use the following command:
php artisan cache:forget [cache-key]
Replace [cache-key] with the key of the cache entry you want to remove.
You can also remove "stale" cache tags (works only with Redis cache) using the following command:
php artisan cache:prune-stale-tags
Clear Config Cache
To clear the Laravel config cache, use this command:
php artisan config:clear
After clearing the config cache, you might want to rebuild it using this command:
php artisan config:cache
Clear Route Cache
To clear the route cache, use the following command:
php artisan route:clear
Afterwards, you might want to run the following command to re-cache the routes:
php artisan route:cache
Clear View Cache
Laravel compiles the views and caches them for faster rendering. To clear view cache:
php artisan view:clear
To rebuild the view cache:
php artisan view:cache
Clear Event Cache
Laravel caches discovered events and listeners. To clear that cache:
php artisan event:clear
After clearning event cache you might want to rebuild it using:
php artisan event:cache
Clear Cache Programmatically (using code)
Laravel offers a cache API that allows you to clear the application cache using PHP code in case you want to do that.
To clear a certain cache entry (with key):
Cache::forget('key');
// or
cache()->forget('key');
To clear all cache:
Cache::flush();
// or
cache()->flush();
Bonus: Optimize
Laravel comes with a new command which caches routes, configs, views and events. So you might rung that command after clearing any of those caches in order to rebuild caches and optimize your application:
php artisan optimize