Laravel is famous for its good architectural approach to design and solving various problems related to security, optimization and scaling. Its place of honor goes to the implementation of caching, at the kernel level, with the help of a large number of ready-made drivers.
In this tutorial we will take a closer look at cache clearing in Laravel, analyze the types and methods of their effective clearing, which will help to effectively manage the cache ensuring maximum performance of your applications.
Understanding Caching Mechanisms
Caching plays an important role in improving performance, this is achieved by storing frequently used data in various storage facilities such as: files, database or individual servers like Redis, Memcached or AWS solutions that reduce the need to re-compute by taking an already stored value.
In order to maximize the efficiency of caching it is necessary to understand all the mechanisms of its operation from creation to deletion. After all, the main problem with caches is that they provide irrelevant data to the user.
Clear the cache ensures that your application uses the latest configuration data, routes and views avoiding unexpected behavior. It is important to choose the right cache lifetime, too long - will create unnecessary load on the server in the form of a large number of files, small - reducing the efficiency of the application. Therefore, choose the right strategy for creating and clear the cache during periods of low server load.
Basically, caching is necessary when you run your application in production mode. For local development, it will only complicate debugging.
The .env
file contains the CACHE_DRIVER
cache driver, which will determine the destination of your cache. Note that setting CACHE_DRIVER=null
will disable the entire application cache, but will not clear it if it was previously enabled.
Caching Types
Laravel uses caching for a variety of purposes and is completely transparent to the user and developer. The internal mechanism of the framework includes caching: configurations, routes, views, events, data cache and compiled classes.
The main directory for storing compiled files is bootstrap/cache
.
Cache clearing methods
Laravel provides several ways to effectively clear the cache, depending on experience and availability and the runtime environment.
Clear Cache via the Artisan Command Line Interface
To clear cached data, the Laravel API uses a cache clearing mechanism using the console interface. Console commands are provided in the framework core to help you update your cache state or clear it completely.
The Illuminate\Foundation\Providers\ArtisanServiceProvider
registers a set of commands when the application is created. Commands such as config:clear
, route:clear
, view:clear
, event:clear
, optimize:clear
, and cache:clear
.
The commands can be invoked in the background or manually using php artisan
. Each command manages its own cache type in isolation and avoids unnecessary clearing of data from other sources.
'CacheClear' => CacheClearCommand::class,
'CacheForget' => CacheForgetCommand::class,
'ClearCompiled' => ClearCompiledCommand::class,
'ConfigCache' => ConfigCacheCommand::class,
'ConfigClear' => ConfigClearCommand::class,
'EventCache' => EventCacheCommand::class,
'EventClear' => EventClearCommand::class,
'Optimize' => OptimizeCommand::class,
'OptimizeClear' => OptimizeClearCommand::class,
'QueueClear' => QueueClearCommand::class,
'QueueFlush' => FlushFailedQueueCommand::class,
'QueueForget' => ForgetFailedQueueCommand::class,
'RouteCache' => RouteCacheCommand::class,
'RouteClear' => RouteClearCommand::class,
'ViewCache' => ViewCacheCommand::class,
'ViewClear' => ViewClearCommand::class,
Manual clearing of cache files
Developers can go to the appropriate directories described earlier and delete cache files.
This method is preferable when there is no access to ssh, but ftp is available. The main thing is to understand what cache you want to clear and where to find files with its contents. If you delete the wrong files, you can always recreate them, so don't worry too much about it.
Clear all caches in Laravel
In order to clear all the cache in an application, you just need to run one command: php artisan optimize:clear
. The command clears the cached load files.
INFO Clearing cached bootstrap files.
events ............................................................ 2ms DONE
views ............................................................. 8ms DONE
cache ............................................................. 5ms DONE
route ............................................................. 1ms DONE
config ............................................................ 1ms DONE
compiled .......................................................... 1ms DONE
Note that when using
supervisor
, runningevents
will continue to run with the old version of the cache. To do this,supervisor
must be reloaded.
Clear Laravel config cache file
Projects have a large number of configuration files and for fastest access they will be combined into one optimized file, reducing disk I/O and improving application performance.
The optimized configuration file can be found at bootstrap/cache/config.php
. It has the appearance of an array within an array.
To clear the cache file, run the php artisan config:clear
command, which will delete the optimized configuration cache file to get fresh data.
To create a shared configuration file again run the php artisan config:cache
command and Laravel will quickly optimize the settings.
After changing configuration files or
.env
always run the cache reset command and you won't run into magic.
Clear Laravel route cache file
All registered routes of the project will be merged into a single file, which will significantly reduce the load on the server for incoming requests.
You can find the optimized configuration file at the path bootstrap/cache/routes-v7.php
.
To clear the routes cache file, run the command php artisan route:clear
. Now you can add new routes and recreate the route cache.
To create a cache file for routes, use the php artisan route:cache
command .
Clear Laravel view cache file
If you have a large project and a large number of templates, such as blade
, you should think about caching views to improve the speed of rendering view content and responsiveness of the application.
The php artisan view:clear
command will clear all compiled view files located in the storage/framework/views
directory.
Run the php artisan view:cache
command to compile all templates (blade, twig) of the application.
The cache stores pre-compiled versions of classes, reducing autoloading overhead and speeding up file load times.
Clear Laravel Application cache
When caching frequently used data or complex calculations, the programmer decides where to put them (file, database, Redis) by defining the CACHE_DRIVER
driver in the .env
file. This is basically key-value
storage with automatic deletion of the value when it expires.
To remove a value from the cache run the command php artisan cache:clear
. Additionally, you can pass the store
and tags
parameters .
To clear only one value, instead of the entire file, run the php artisan cache:forget <key> [<store>]
command .
Programmatically clearing the Laravel application cache
To programmatically clear the Laravel application cache, you can use the Illuminate\Support\Facades\Cache
facade or the cache()
helper function.
Cache::forget('key')
andcache()->forget('key')
to remove the specified key from the repository, both commands perform the same action.Cache::flush()
andcache()->flush()
- clear the storage completely, the commands are equivalent in action
Clear Laravel event cache files
Events and listeners are very useful helpers for any application and quick access to them will noticeably improve the performance of the whole project.
You can find the optimized configuration file at the path bootstrap/cache/events.php
.
To clear the event cache, run the php artisan event:clear
command, which will delete the events.php
file .
Run the php artisan event:cache
command to optimize your communication channels.
Clear Laravel schedule tasks cache file
Executing scheduled tasks using crontab helps to optimize business processes and proper caching helps to increase the fault tolerance of the entire application by using up to date cache version.
To clear the cache of scheduled tasks, you need to run the php artisan schedule:clear-cache
command .
Clear Laravel cache through web browser
For quick access to cache management, a useful new route would be to clear the cache on demand from the browser using the Artisan
command line interface .
Route::get('/cache-clear', function() {
Artisan::call('optimize:clear');
// TODO cler anything else
return response()->json(['ok' => true]);
});
Cache Management Best Practices
Utilizing best practices is key to a fault-tolerant and reliable application with high performance. Best practices include:
- regular cache cleanup during local development
- clearing the cache during production mode and deploying changes
- monitoring cache utilization and performance to prevent data obsolescence
- cache anything that is computationally intensive or frequently used
Bottom line
In this article we have covered the principles of Laravel caching system, cache types and how to clean different types of caches such as configuration, views, routes and application caches.
Note that using a cache is a great way to optimize the performance of any application, improving performance several times over. By following the guidelines and best practices you will forget about the problems of magic code and irrelevant data.
Be sure to enable caching on your projects and don't forget to clean and analyze it in time.