Caching in Laravel 8/9 with Example

In this tutorial, you will about caching in Laravel 8/9 with example.

Caching is a very powerful tool that helps to store frequently needed data in a very fast data store so that the data can be retrieved quickly on subsequent requests for the same information.

Laravel supports caching by providing a powerful, unified API for numerous cache backends, allowing web applications to benefit from lightning-fast data retrieval.

In Laravel, the cache configuration file is located at config/cache.php.

Laravel has built-in support for Memcached, Redis, DynamoDB, and relational databases, as well as other common caching backends. Laravel also supports a file-based cache driver, as well as array and "null" cache drivers that provides simple cache backends for automated tests.

Laravel is set up to use the file cache driver by default, which saves serialized, cached objects to the server's filesystem. However, more robust driver, such as Memcached or Redis should be used for larger applications. We can even set up numerous cache settings for the same driver.

In Laravel, file based cached objects are stored at storage/framework/cache/.

File-based Caching

The following is a File-based caching example in Laravel:


<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
    /**
     * Stores rate limit exceeded ip in file cache
     * 
     */
    public function cacheIP(Request $request)
    {
        $userIp = $request->ip();
        $expiresAt = Carbon::now()->addMinutes(10);
        $key = $userIp;
        $value = 1;

        //Adding new item to cache for no longer than 10 minutes
        Cache::add($key, $value, $expiresAt);

        //Checking if the userIp is already in cache
        if (Cache::has($userIp)) {

            //Retrieving ip from cache
            $rateLimitedIp = Cache::get($userIp, 0);

            Log::info("rateLimitedIp from cache : " . $rateLimitedIp);
            if ($rateLimitedIp == 1) {
            } else {
            }
        }
    }
}

Storing Items If Not Present

The add method only adds an item to the cache if it does not already exist in the cache store. This method returns true if the item is added to the cache, otherwise it returns false. We can also pass DateTime instance representing the cached item's desired expiration time:


$expiresAt = Carbon::now()->addMinutes(10);    
Cache::add($key, $value, $expiresAt);

Storing Items Forever

The forever method stores an item in the cache permanently:


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

Retrieving Items from the Cache

The get method retrieves an item from the cache. It returns null if the item is not present in the cache:


Cache::get('key', 'defaultValue');

Removing Items from the Cache

The forget method removes the item with the specified key from the cache:


Cache::forget('key');

Clearing Entire Cache

The flush method deletes everything from the cache:


Cache::flush();