PHPackages                             hashtap/laravel-responsecache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. hashtap/laravel-responsecache

ActiveLibrary[Caching](/categories/caching)

hashtap/laravel-responsecache
=============================

Speed up a Laravel application by caching the entire response

6.6.3(5y ago)049MITPHPPHP ^7.2

Since Jul 16Pushed 5y agoCompare

[ Source](https://github.com/hashtap/laravel-responsecache)[ Packagist](https://packagist.org/packages/hashtap/laravel-responsecache)[ Docs](https://github.com/hashtap/laravel-responsecache)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/hashtap-laravel-responsecache/feed)WikiDiscussions master Synced yesterday

READMEChangelog (1)Dependencies (6)Versions (55)Used By (0)

Speed up an app by caching the entire response
==============================================

[](#speed-up-an-app-by-caching-the-entire-response)

[![Latest Version on Packagist](https://camo.githubusercontent.com/5f7668c5bc5a54dcc44365d044b0e9a21d75528a6ceec0dd591451f32c2052b4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f686173687461702f6c61726176656c2d726573706f6e736563616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hashtap/laravel-responsecache)[![MIT Licensed](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Psalm](https://github.com/hashtap/laravel-responsecache/workflows/psalm/badge.svg)](https://github.com/hashtap/laravel-responsecache/workflows/psalm/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/ee3d979f07f20607107f89c9e3a93b5f519c6da4253718f2880c7a6005ecef38/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686173687461702f6c61726176656c2d726573706f6e736563616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hashtap/laravel-responsecache)

This Laravel package can cache an entire response. 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 respond with the saved response.

Are you a visual learner? Then watch [this video](https://spatie.be/videos/spatie-package-source-dives/laravel-responsecache) that covers how you can use laravel-responsecache and how it works under the hood.

Installation
------------

[](#installation)

You can install the package via composer:

```
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"
```

This is the contents of the published config file:

```
// config/responsecache.php

return [
    /*
     * Determine if the response cache middleware should be enabled.
     */
    'enabled' => env('RESPONSE_CACHE_ENABLED', true),

    /*
     *  The given class will determinate if a request should be cached. The
     *  default class will cache all successful GET-requests.
     *
     *  You can provide your own class given that it implements the
     *  CacheProfile interface.
     */
    'cache_profile' => Spatie\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests::class,

    /*
     * When using the default CacheRequestFilter this setting controls the
     * default number of seconds responses must be cached.
     */
    'cache_lifetime_in_seconds' => env('RESPONSE_CACHE_LIFETIME', 60 * 60 * 24 * 7),

    /*
     * This setting determines if a http header named with the cache time
     * should be added to a cached response. This can be handy when
     * debugging.
     */
    'add_cache_time_header' => env('APP_DEBUG', true),

    /*
     * This setting determines the name of the http header that contains
     * the time at which the response was cached
     */
    'cache_time_header_name' => env('RESPONSE_CACHE_HEADER_NAME', 'laravel-responsecache'),

    /*
     * Here you may define the cache store that should be used to store
     * requests. This can be the name of any store that is
     * configured in app/config/cache.php
     */
    'cache_store' => env('RESPONSE_CACHE_DRIVER', 'file'),

    /*
     * Here you may define replacers that dynamically replace content from the response.
     * Each replacer must implement the Replacer interface.
     */
    'replacers' => [
        \Spatie\ResponseCache\Replacers\CsrfTokenReplacer::class,
    ],

    /*
     * If the cache driver you configured supports tags, you may specify a tag name
     * here. All responses will be tagged. When clearing the responsecache only
     * items with that tag will be flushed.
     *
     * You may use a string or an array here.
     */
    'cache_tag' => '',

    /*
     * This class is responsible for generating a hash for a request. This hash
     * is used to look up an cached response.
     */
    'hasher' => \Spatie\ResponseCache\Hasher\DefaultHasher::class,

    /*
     * This class serializes cache data and expands it.
     * Serialization can save the data to be returned in an appropriate form.
     */
    'serializer' => \Spatie\ResponseCache\Serializer\DefaultSerializer::class,
];
```

And finally you should install the provided middlewares `\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
-----

[](#usage)

### Basic usage

[](#basic-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 behaviour is what you need, you're done: installing the `ResponseCacheServerProvider` was enough.

### Clearing the cache

[](#clearing-the-cache)

#### Manually

[](#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

[](#using-a-console-command)

The same can be accomplished by issuing this artisan command:

```
php artisan responsecache:clear
```

#### Using model events

[](#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 URI(s)

[](#forget-one-or-several-specific-uris)

You can forget specific URIs with:

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

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

// Alternatively
ResponseCache::forget('/some-uri', '/other-uri');
```

The `forget` method only works when you're not using a `cacheNameSuffix` in your cache profile.

### Preventing a request from being cached

[](#preventing-a-request-from-being-cached)

Requests can be ignored by using the `doNotCacheResponse`-middleware. This middleware [can be assigned to routes and controllers](http://laravel.com/docs/master/controllers#controller-middleware).

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']]);
    }
}
```

### Creating a custom cache profile

[](#creating-a-custom-cache-profile)

To determine which requests should be cached, and for how long, a cache profile class is used. The default class that handles these questions is `Spatie\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests`.

You can create your own cache profile class by implementing the ` Spatie\ResponseCache\CacheProfiles\CacheProfile`-interface. Let's take a look at the interface:

```
interface CacheProfile
{
    /*
     * Determine if the response cache middleware should be enabled.
     */
    public function enabled(Request $request): bool;

    /*
     * Determine if the given request should be cached.
     */
    public function shouldCacheRequest(Request $request): bool;

    /*
     * Determine if the given response should be cached.
     */
    public function shouldCacheResponse(Response $response): bool;

    /*
     * Return the time when the cache must be invalidated.
     */
    public function cacheRequestUntil(Request $request): DateTime;

    /**
     * Return a string to differentiate this request from others.
     *
     * For example: if you want a different cache per user you could return the id of
     * the logged in user.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function useCacheNameSuffix(Request $request);
}
```

### Caching specific routes

[](#caching-specific-routes)

Instead of registering the `cacheResponse` middleware globally, you can also register it as route middleware.

```
protected $routeMiddleware = [
   ...
   'cacheResponse' => \Spatie\ResponseCache\Middlewares\CacheResponse::class,
];
```

When using the route middleware you can specify the number of seconds these routes should be cached:

```
// cache this route for 5 minutes
Route::get('/my-special-snowflake', 'SnowflakeController@index')->middleware('cacheResponse:300');

// cache all these routes for 10 minutes
Route::group(function() {
   Route::get('/another-special-snowflake', 'AnotherSnowflakeController@index');

   Route::get('/yet-another-special-snowflake', 'YetAnotherSnowflakeController@index');
})->middleware('cacheResponse:600');
```

### Using tags

[](#using-tags)

If the [cache driver you configured supports tags](https://laravel.com/docs/5.8/cache#cache-tags), you can specify a list of tags when applying the middleware.

```
// add a "foo" tag to this route with a 300 second lifetime
Route::get('/test1', 'SnowflakeController@index')->middleware('cacheResponse:300,foo');

// add a "bar" tag to this route
Route::get('/test2', 'SnowflakeController@index')->middleware('cacheResponse:bar');

// add both "foo" and "bar" tags to these routes
Route::group(function() {
   Route::get('/test3', 'AnotherSnowflakeController@index');

   Route::get('/test4', 'YetAnotherSnowflakeController@index');
})->middleware('cacheResponse:foo,bar');
```

#### Clearing tagged content

[](#clearing-tagged-content)

You can clear responses which are assigned a tag or list of tags. For example, this statement would remove the `'/test3'` and `'/test4'` routes above:

```
ResponseCache::clear(['foo', 'bar']);
```

In contrast, this statement would remove only the `'/test2'` route:

```
ResponseCache::clear(['bar']);
```

Note that this uses [Laravel's built in cache tags](https://laravel.com/docs/master/cache#cache-tags) functionality, meaning routes can also be cleared in the usual way:

```
Cache::tags('special')->flush();
```

### Events

[](#events)

There are several events you can use to monitor and debug response caching in your application.

#### ResponseCacheHit

[](#responsecachehit)

`Spatie\ResponseCache\Events\ResponseCacheHit`

This event is fired when a request passes through the `ResponseCache` middleware and a cached response was found and returned.

#### CacheMissed

[](#cachemissed)

`Spatie\ResponseCache\Events\CacheMissed`

This event is fired when a request passes through the `ResponseCache` middleware but no cached response was found or returned.

#### ClearingResponseCache and ClearedResponseCache

[](#clearingresponsecache-and-clearedresponsecache)

`Spatie\ResponseCache\Events\ClearingResponseCache`

`Spatie\ResponseCache\Events\ClearedResponseCache`

These events are fired respectively when the `responsecache:clear` is started and finished.

### Creating a Replacer

[](#creating-a-replacer)

To replace cached content by dynamic content, you can create a replacer. By default we add a `CsrfTokenReplacer` in the config file.

You can create your own replacers by implementing the `Spatie\ResponseCache\Replacers\Replacer`-interface. Let's take a look at the interface:

```
interface Replacer
{
    /*
     * Transform the initial response before it gets cached.
     *
     * For example: replace a generated csrf_token by '' that you can
     * replace with its dynamic counterpart when the cached response is returned.
     */
    public function transformInitialResponse(Response $response): void;

    /*
     * Replace any data you want in the cached response before it gets
     * sent to the browser.
     *
     * For example: replace '' by a call to csrf_token()
     */
    public function replaceCachedResponse(Response $response): void;
}
```

Afterwards you can define your replacer in the `responsecache.php` config file:

```
/*
 * Here you may define replacers that dynamically replace content from the response.
 * Each replacer must implement the Replacer interface.
 */
'replacers' => [
    \Spatie\ResponseCache\Replacers\CsrfTokenReplacer::class,
],

```

### Customizing the serializer

[](#customizing-the-serializer)

A serializer is responsible from serializing a response so it can be stored in the cache. It is also responsible for rebuilding the response from the cache.

The default serializer `Spatie\ResponseCache\Serializer\DefaultSerializer` will just work in most cases.

If you have some special serialization needs you can specify a custom serializer in the `serializer` key of the config file. Any class that implements `Spatie\ResponseCache\Serializers\Serializer` can be used. This is how that interface looks like:

```
namespace Spatie\ResponseCache\Serializers;

use Symfony\Component\HttpFoundation\Response;

interface Serializer
{
    public function serialize(Response $response): string;

    public function unserialize(string $serializedResponse): Response;
}
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Testing
-------

[](#testing)

You can run the tests with:

```
composer test
```

Alternatives
------------

[](#alternatives)

- [Barry Vd. Heuvel](https://twitter.com/barryvdh) made [a package that caches responses by leveraging HttpCache](https://github.com/barryvdh/laravel-httpcache).
- [Joseph Silber](https://twitter.com/joseph_silber) created [Laravel Page Cache](https://github.com/JosephSilber/page-cache) that can write it's cache to disk and let Nginx read them, so PHP doesn't even have to start up anymore.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 75.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~37 days

Recently: every ~30 days

Total

50

Last Release

2140d ago

Major Versions

v2.x-dev → 3.0.02017-03-16

v3.x-dev → 4.0.02017-08-30

4.4.4 → v5.x-dev2018-10-18

4.4.5 → 5.0.02019-02-27

5.0.3 → 6.0.02019-05-20

PHP version history (6 changes)0.0.1PHP &gt;=5.5.0

v1.x-devPHP &gt;=5.6.0

3.0.1PHP ^7.0

5.0.0PHP ^7.2

6.0.0PHP ^7.3

6.4.0PHP ^7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/1cb105fd077387eb1c77d17f9729345b4d3e053eba6bd9e2fce3f36bdf62749e?d=identicon)[hashtap](/maintainers/hashtap)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (199 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (19 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (9 commits)")[![atymic](https://avatars.githubusercontent.com/u/50683531?v=4)](https://github.com/atymic "atymic (3 commits)")[![atldays](https://avatars.githubusercontent.com/u/130153594?v=4)](https://github.com/atldays "atldays (3 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (3 commits)")[![JoeyHoutenbos](https://avatars.githubusercontent.com/u/1810441?v=4)](https://github.com/JoeyHoutenbos "JoeyHoutenbos (2 commits)")[![dam1r89](https://avatars.githubusercontent.com/u/3540487?v=4)](https://github.com/dam1r89 "dam1r89 (2 commits)")[![michelecurletta](https://avatars.githubusercontent.com/u/65455871?v=4)](https://github.com/michelecurletta "michelecurletta (2 commits)")[![sdebacker](https://avatars.githubusercontent.com/u/134503?v=4)](https://github.com/sdebacker "sdebacker (2 commits)")[![Omranic](https://avatars.githubusercontent.com/u/406705?v=4)](https://github.com/Omranic "Omranic (1 commits)")[![richardkeep](https://avatars.githubusercontent.com/u/3874381?v=4)](https://github.com/richardkeep "richardkeep (1 commits)")[![stevebauman](https://avatars.githubusercontent.com/u/6421846?v=4)](https://github.com/stevebauman "stevebauman (1 commits)")[![svenluijten](https://avatars.githubusercontent.com/u/11269635?v=4)](https://github.com/svenluijten "svenluijten (1 commits)")[![swapnilsarwe](https://avatars.githubusercontent.com/u/166912?v=4)](https://github.com/swapnilsarwe "swapnilsarwe (1 commits)")[![thequiet](https://avatars.githubusercontent.com/u/3046725?v=4)](https://github.com/thequiet "thequiet (1 commits)")[![trollderiu](https://avatars.githubusercontent.com/u/216930211?v=4)](https://github.com/trollderiu "trollderiu (1 commits)")[![tuimz](https://avatars.githubusercontent.com/u/850235?v=4)](https://github.com/tuimz "tuimz (1 commits)")[![vv12131415](https://avatars.githubusercontent.com/u/17382248?v=4)](https://github.com/vv12131415 "vv12131415 (1 commits)")[![0xK4d1r](https://avatars.githubusercontent.com/u/15370532?v=4)](https://github.com/0xK4d1r "0xK4d1r (1 commits)")

---

Tags

responsespatielaravelperformancecachelaravel-responsecache

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/hashtap-laravel-responsecache/health.svg)

```
[![Health](https://phpackages.com/badges/hashtap-laravel-responsecache/health.svg)](https://phpackages.com/packages/hashtap-laravel-responsecache)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[maartenstaa/laravel-41-route-caching

This package allows you to cache your routes definitions, thereby speeding up each request.

25371.9k](/packages/maartenstaa-laravel-41-route-caching)[anahkiasen/flatten

A package for the Illuminate framework that flattens pages to plain HTML

33313.0k](/packages/anahkiasen-flatten)[flc/laravel-middleware-cache-response

Laravel中间件-Response缓存

608.2k](/packages/flc-laravel-middleware-cache-response)[omaralalwi/lexi-translate

Laravel translation package with morph relationships and caching.

754.3k2](/packages/omaralalwi-lexi-translate)[byerikas/cache-tags

Allows for Redis/Valkey cache flushing multiple tagged items by a single tag.

1413.9k](/packages/byerikas-cache-tags)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
