Blog Detail

30

Dec
Speed up your Laravel App by Caching the Entire Response cover image

arrow_back Speed up your Laravel App by Caching the Entire Response

Laravel-responsecache is a package by Spatie that can cache an entire response and speed up your applications. By default, it will cache all successful get-requests that return text-based content (such as HTML and json) for a week. This could potentially speed up the response quite considerably. So the first time a request comes in the package will save the response before sending it to the users. When the same request comes in again we’re not going through the entire application but just responding with the saved response.

Installation

Note: If you’re using PHP 7, install v6.x of this package.

You can install this package via composer, Just run this command in the terminal:

composer require spatie/laravel-responsecache

The package will automatically register itself.

You can publish the config file with:

php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider"

And finally you should register the provided middleware \Spatie\ResponseCache\Middlewares\CacheResponse::class and \Spatie\ResponseCache\Middlewares\DoNotCacheResponse in the http kernel.

// app/Http/Kernel.php

protected $middlewareGroups = [
   'web' => [
       \Spatie\ResponseCache\Middlewares\CacheResponse::class,
   ],


protected $routeMiddleware = [
  
   'doNotCacheResponse' => \Spatie\ResponseCache\Middlewares\DoNotCacheResponse::class,
];

Usage

By default, the package will cache all successful GET requests for a week. Logged-in users will each have their own separate cache. If this behavior is what you need, you’re done: installing the ResponseCacheServiceProvider was enough.

Clearing the cache

Manually

The entire cache can be cleared with:

ResponseCache::clear();

This will clear everything from the cache-store specified in the config file.

Using a console command

The same can be accomplished by issuing this artisan command:

php artisan responsecache:clear

Using model events

You can leverage model events to clear the cache whenever a model is saved or deleted. Here’s an example.

namespace App\Traits;

use Spatie\ResponseCache\Facades\ResponseCache;

trait ClearsResponseCache
{
    public static function bootClearsResponseCache()
    {
        self::created(function () {
            ResponseCache::clear();
        });

        self::updated(function () {
            ResponseCache::clear();
        });

        self::deleted(function () {
            ResponseCache::clear();
        });
    }
}

Forget one or several specific URIs

You can forget specific URIs with:

// Forget one
ResponseCache::forget('/some-uri');

// Forget several
ResponseCache::forget(['/some-uri', '/other-uri']);

// Equivalent to the example above
ResponseCache::forget('/some-uri', '/other-uri');

The ResponseCache::forget method only works when you’re not using a cacheNameSuffix in your cache profile, use ResponseCache::selectCachedItems to deal with cacheNameSuffix.

Forgetting a selection of cached items

You can use ResponseCache::selectCachedItems() to specify which cached items should be forgotten.

// forgetting all PUT responses of /some-uri
ResponseCache::selectCachedItems()->withPutMethod()->forUrls('/some-uri')->forget();

// forgetting all PUT responses of multiple endpoints
ResponseCache::selectCachedItems()->withPutMethod()->forUrls(['/some-uri','/other-uri'])->forget();

// this is equivalent to the example above
ResponseCache::selectCachedItems()->withPutMethod()->forUrls('/some-uri','/other-uri')->forget();

// forget /some-uri cached with "100" suffix (by default suffix is user->id or "")
ResponseCache::selectCachedItems()->usingSuffix('100')->forUrls('/some-uri')->forget();

// all options combined
ResponseCache::selectCachedItems()
    ->withPutMethod()
    ->withHeaders(['foo'=>'bar'])
    ->withCookies(['cookie1' => 'value'])
    ->withParameters(['param1' => 'value'])
    ->withRemoteAddress('127.0.0.1')
    ->usingSuffix('100') 
    ->usingTags('tag1', 'tag2')
    ->forUrls('/some-uri', '/other-uri')
    ->forget();

The cacheNameSuffix depends on your cache profile, by default is the user ID or an empty string if not authenticated.

Preventing a request from being cached

Requests can be ignored by using the doNotCacheResponse middleware. This middleware can be assigned to routes and controllers.

Using the middleware are route could be exempt from being cached.

// app/Http/routes.php

Route::get('/auth/logout', ['middleware' => 'doNotCacheResponse', 'uses' => 'AuthController@getLogout']);

Alternatively, you can add the middleware to a controller:

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('doNotCacheResponse', ['only' => ['fooAction', 'barAction']]);
    }
}

With the help of this package, you can also create a custom cache profile. There are also many other options and events are available in this package. If you want to dig more you can visit its complete documentation on Github.

Published at : 30-12-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project