Laravel Caching & How It Can
Boost the Performance

Muhammad Sanan
4 min readApr 28, 2023

--

Laravel gives us a very easy way to manage the application cache and makes it an efficient tool for increasing the performance of the application. All the configuration for the cache is located in config/cache.php. In this file, you may specify which cache driver or store to use by default throughout your application. Laravel supports popular caching backends like Memcached, Redis, DynamoDB, file, and relational databases out of the box.

By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects on the server's filesystem. We will not go into driver configuration and use the default file driver for our example as it can vary according to different factors like application scale and complexity. Any driver can be easily configured by reading the documentation. Please note that if you are using the database driver, you need to create a table in the database, the migration for which can be created using the following command.

php artisan cache:table

METHODS

We can manage the application cache in the following two ways.

  1. Cache Facade
  2. cache() helper function

CACHE OPERATIONS

//store items in the cache
Cache::put('key', 'value', $seconds = 10);

//store item indefinitely
Cache::put('key', 'value');

//pass a DateTime instance as expiration time
Cache::put('key', 'value', now()->addMinutes(10));

//add the item to the cache if it does not already exist
Cache::add('key', 'value', $seconds);

//store an item in the cache permanently.
Cache::forever('key', 'value');

//get item from cache using key
$value = Cache::get('key');

//pass a default value that will be returned if the item is not found
$value = Cache::get('key', 'default');

//pass a closure as the default value.
$value = Cache::get('key', function () {
return DB::table(/* ... */)->get();
});

//determine if an item exists. also returns false if item’s value is null
Cache::has('key')

//adjust the value of integer items in the cache.
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);

//retrieve an item from the cache and then delete the item
$value = Cache::pull('key');

//remove items from the cache
Cache::forget('key');

remove items by providing a zero or negative number of expiration seconds
Cache::put('key', 'value', 0);
Cache::put('key', 'value', -5);

//clear the entire cache
Cache::flush();

ACCESSING MULTIPLE STORES

Using the Cache facade, you can access various cache stores from the ‘stores’ configuration array in your cache configuration file via the store method.

$value = Cache::store('file')->get('foo');
Cache::store('redis')->put('bar', 'baz', 600); // 10 Minutes

TAGS

You can assign tags to a cached value while putting it into the cache

Cache::tags(['people', 'artists'])->put('John', $john, $seconds);

To retrieve a tagged cache item, pass the same ordered list of tags to the tags method.

$john = Cache::tags(['people', 'artists'])->get('John');

You may only flush all items that are assigned a tag or a list of tags. Other cache items that do not use the same tags will not be flushed.

Cache::tags(['people', 'artists'])->flush();

HOW CACHES CAN BOOST PERFORMANCE

As most of you know, caches are very fast and small compared to regular storage so using them efficiently will make your application very fast. Try to use cache storage for all your temporary memory needs as much as you can. There are also a couple of other functions available that we have not yet discussed. Let’s see how they can improve our application’s performance.

As most of you already know laravel provides us with commands to cache things like:

php artisan route:cache //cache routes
php artisan route:clear //clear route cache

php artisan view:cache //cache views
php artisan view:clear //clear view cache

php artisan config:cache //cache config
php artisan config:clear //clear config cach

This default caching increases the performance but make sure to clear the cache after deploying changes. This is fine but we have another important type of caching that we can do and that can be called query caching.

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn’t exist. For example, you may wish to retrieve all users from the cache or, if they don’t exist, retrieve them from the database and add them to the cache. You may do this using the Cache::remember method.

$users = Cache::remember('users', $seconds, function () {
return DB::table('users')->get();
});

Now to better understand, let’s discuss a scenario. Suppose you want to get all users from the database multiple times in a small amount of time and the number of records is huge and the records are not updated frequently. If we get users from the database every time, it would take a lot of time to run the query again and again. So we can theoretically get the users once and store them in the cache and then retrieve them from the cache whenever we need. We can set a time interval and they will remain in the cache for only the specified amount of time so that after that time has passed and a request is made to get all users, there will be no data present in the cache in which case updated users data will be fetched from the database and then stored in the cache so we don’t keep getting outdated data.

You may use the rememberForever method to retrieve an item from the cache or store it forever if it does not exist. This is not recommended if your application is using dynamic and changing data as you will keep getting outdated data from the cache rather than getting updated data. Also, caches are meant to be temporary storage.

$value = Cache::rememberForever('users', function () {
return DB::table('users')->get();
});

--

--

Muhammad Sanan

Agile Dev specializing in PHP, Laravel, & JS. Tech blogger & mentor with a passion for coding and innovation. Let's create impactful solutions together.