Caching using Eloquent events in Laravel 5.4Feb 14, 2017
On this article I'm going to share you one of the package I wrote recently to effectively do caching using eloquent events in laravel 5.4. While working on one of my project, I found that updating the cache values during creation/updation/deletion is quite painful. So, Laravel Model Cacher is the package I wrote to do caching easily.
First lets install the package
composer require sarav/model-cacher
after installing, add the below service provider to the config/app.php file.
Once it is added, now do vendor publish to publish the configuration file for the package.
php artisan vendor:publish --tag=laravel-model-cacher --force
Note: If vendor publish isn't working try clearing cache by issuing
php artisan config:cache
Now if you open the cacheable file under the config folder, you will find the following array.
Here model array holds the list of models that you wanted to listen to when eloquent events are triggerd. Without adding the models here, eloquent events for the model won't be listened.
Then, minutes denotes the number of minutes you wanted the value to be cached.
CacheHandler trait for the model you wanted to manage the caching
$cacheAll denotes that you wanted to cache the entire table and store them.
$cacheName denotes the name of the cache you are assigning.
You can also do individual caching by replace $cacheAll with
$individualCache = $true;
Now, you can easily retrieve the values like the following code.
Now cache will get created/updated/deleted based on your eloquent events.
You can also modify which columns you wanted to get cached instead of whole table getting cached. To do so, simply add the following method to your model and passing the necessary columns to select method on the query.
Thats it! Thats all you need to do to effectively manage caching using eloquent events in laravel 5.4.