Everything You Need to Know About Laravel Caching

The cache is used to store data in a temporary or permanent environment for better performance and user experience. Caching is essential for achieving high performance and scalability. Setting up proper caching can reduce the load on the server and is helpful for minimal page response time. Laravel has in-built caching functionality with multiple options.

In this article, we will learn more about caching and implement caching in our application.

While learning about cache, it’s common to think about why caching is required. With the help of caching, you can provide minimal load time which helps your SEO strategy. As per Google, if your response time is lower then there are better chances to be at the top of the search engine result page.

What Is Laravel Caching?

Laravel provides a robust and easy-to-use implementation of caching with different caching drivers like Database, Memcached, Redis, and DynamoDB. In Laravel cache, you can use caching functionality by writing minimal code or almost no code.

Setting up Cache In Laravel application

Before using cache in Laravel, you need to configure caching in the Laravel application. The first thing is driver configuration into the .env file.

CACHE_DRIVER=file

You can use any cache driver as per your requirement by default file driver is configured. But before changing the database driver, there are things to configure as per your selected driver. For example, if you are using a database driver to store cache then you need to create a table for storing cache data. Using the Memcached driver requires the Memcached PECL package to be installed.

In this example, we will use a database driver. To create a cache table in our database either we create a new migration or use the php artisan cache:table command to create a migration file.

Schema::create('cache', function ($table) {
    $table->string('key')->unique();
    $table->text('value');
    $table->integer('expiration');
});

Retreiveing Cache Value

To access the cache store instance, we will use the Cache facade. With a cache facade, we can use all cache-related methods as abstract methods. we just have to use Illuminate\Support\Facades\Cache;

To get cache values, we will use the get() method. Cache’s get method is just like the session’s get method. You can get value by key and also configure it for default value if a relevant key is not found. We just have to pass the second argument as the default value.

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class HomeController extends Controller
{
    public function index()
    {
        $userSelection = Cache::get('choice');
		//or
		$userSelection = Cache::get('choice', 'default');
    }
}

Checking For Item Existence

Sometimes, we need to check key exists in the cache and perform actions based on the result. By using the has() method, we can determine particular key exists in the cache instance or not. it will return true or false based. If but value of a key is null then it will also return false.

if (Cache::has('choice')) {
    //Perform Specific operation
}

Incrementing / Decrementing Values

Sometimes we are required to perform increment or decrement value of a particular cache. For example, if we are counting page views for users and storing those page views in cache then we can use the increment method. Suppose we have given a trial of a particular service for limited requests then we can use the decrement method.

Here, we can also specify increment or decrement amount by passing as a second parameter.

Cache::increment('viewCount');
Cache::increment('viewCount', 2);
Cache::decrement('viewCount');
Cache::decrement('viewCount', 4);

Storing Data In Cache

To store data in a cache, we will use the put() method on the cache facade. The put method will take three parameters. First is the key, second is value and the third one is time in the second or Date Time object to set expiry time.

Cache::put('key', 'value', $seconds = 60);
//or
Cache::put('key', 'value');

Here, if time is not passed then it will store it indefinitely. For a time, we can pass the date time object as expiry time like the below example :

Cache::put('key', 'value', now()->addMinutes(60));

To store cache data permanently, you can use the forever() method. To remove this cache data, you need to perform the forget method manually.

Cache::forever('key', 'value');

The add method will only add the item to the cache if it does not exist in the cache store. It’s used when we are required to store data if it does not exist.

Cache::add('key', 'value', $seconds = 60);

Removing Cache Data In Laravel

You can remove cache data using multiple methods like forget, put, or flush.

The forget method, will take the key as a parameter and remove it from the cache instance.

Cache::forget('key');

We can also use the put method to remove the cache. But in the put method, we update the expiry time for particular data in negative or zero. So it will be automatically removed.

Cache::put('key', 'value', 0);
//or
Cache::put('key', 'value', -10);

The flush method will be used when we want to clear all cache data. It will clear the entire cache instance.

Cache::flush();

Conclusion

Here, We have taken short examples for storing, retrieving, or deleting cache in the Laravel application. There are plenty of other concepts to use cache for better optimization. We will learn more about those in further tutorials.