Caching using Eloquent events in Laravel 5.4

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.

 

Installation

 
First lets install the package

composer require sarav/model-cacher
 
after installing, add the below service provider to the config/app.php file.
 
Sarav\Providers\ModelCacherServiceProvider::class
 
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

 

Configuring cacheable.php

 
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.
 

Configuring model

 
Add the CacheHandler trait for the model you wanted to manage the caching
 

 

Here $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;
 

 

Retreiving Values

 
Now, you can easily retrieve the values like the following code.
 

 

Now cache will get created/updated/deleted based on your eloquent events.

 

Modify Query

 
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.

 


I'm a full stack freelance PHP developer. I have worked on various PHP frameworks like Laravel, Code Igniter, Magento, Wordpress.