PHPackages                             matchory/response-cache - 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. matchory/response-cache

ActiveLibrary[Caching](/categories/caching)

matchory/response-cache
=======================

A package to add automatic response caching to Laravel APIs.

1.5.2(1y ago)212.7k—8%1MITPHPPHP &gt;=8.2

Since Mar 31Pushed 1y ago1 watchersCompare

[ Source](https://github.com/matchory/response-cache)[ Packagist](https://packagist.org/packages/matchory/response-cache)[ RSS](/packages/matchory-response-cache/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (20)Used By (0)

Response Cache [![Latest Stable Version](https://camo.githubusercontent.com/4ecba77f098b12c39db02ec659e2d23c9c873601ad3e78848fea4ab45496d578/68747470733a2f2f706f7365722e707567782e6f72672f6d617463686f72792f726573706f6e73652d63616368652f76)](https://packagist.org/packages/matchory/response-cache) [![Total Downloads](https://camo.githubusercontent.com/345d283fdfe9f53b0251b9d173c4a7d2e84cb4221c7592dfa5f559aa1a96372b/68747470733a2f2f706f7365722e707567782e6f72672f6d617463686f72792f726573706f6e73652d63616368652f646f776e6c6f616473)](https://packagist.org/packages/matchory/response-cache) [![Latest Unstable Version](https://camo.githubusercontent.com/2813a40ea3e47992b16d782b40772e1564002dfb32c7f8b17e36c5f4f500c972/68747470733a2f2f706f7365722e707567782e6f72672f6d617463686f72792f726573706f6e73652d63616368652f762f756e737461626c65)](https://packagist.org/packages/matchory/response-cache) [![License](https://camo.githubusercontent.com/27aecc389b32efcbf23abbd7aa8f2ac8d81bdec59036fe631304f69e9948d21c/68747470733a2f2f706f7365722e707567782e6f72672f6d617463686f72792f726573706f6e73652d63616368652f6c6963656e7365)](https://packagist.org/packages/matchory/response-cache) [![Laravel Octane Compatible](https://camo.githubusercontent.com/70359a356da237cd29561bc5d0bb80baae775b5ff62f288ed324755382858342/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2532304f6374616e652d436f6d70617469626c652d737563636573733f7374796c653d666c6174266c6f676f3d6c61726176656c)](https://github.com/laravel/octane)
======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#response-cache-----)

> A Laravel package that adds a smart cache for full responses

Using this package, you can cache full response instances returned from your controllers, simply by adding a middleware.
This can speed up your application immensely!

Features
--------

[](#features)

- **Easy to use**: Just [add the `CacheResponse`](#using-the-responsecache-middleware-manually) to your route!
- **Fully customizable**: The cache probably works out of the box, but you can control every aspect of caching if necessary.
- **Support for authenticated requests**: By default, cache entries will be unique to every authenticated user.
- **Resolves route bindings in tags**: Cache tags may use any value in the route or request data dynamically.

```
Route::get('/example')->middleware([
    'cacheResponse:3600,examples'
])
```

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

[](#alternatives)

Coincidentally, I just learned [spatie](https://spatie.be/) have built almost exactly the same library as we did:
[spatie/laravel-responsecache](https://github.com/spatie/laravel-responsecache).

### Why not use Varnish?

[](#why-not-use-varnish)

In contrast to external caches, having the response cache in your app gives you the power to evaluate route bindings, authentication state, and easy programmatic cache flushing.
This also makes it possible to place the cache check anywhere in your middleware stack!

Requirements
------------

[](#requirements)

- **PHP 8.0 or later**
- Laravel 7.x or later

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

[](#installation)

Install using composer:

```
composer require matchory/response-cache
```

Unless you have disabled package discovery, everything should be set up already. Otherwise, add the service provider and the facade to your configuration.

Optionally, you can publish the configuration file:

```
php artisan vendor:publish --provider "Matchory\ResponseCache\ResponseCacheProvider"
```

Check out the [configuration section](#configuration) to learn about all available options.

Add the middleware to your `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
   'web' => [
       // ...
       \Matchory\ResponseCache\Http\Middleware\CacheResponse::class,
       // ...
   ],
];

protected $routeMiddleware = [
    // ...
    'bypass_cache' => \Matchory\ResponseCache\Http\Middleware\BypassCache::class,
    // ...
];
```

Configuration
-------------

[](#configuration)

The config file contains the following settings:

### `enabled` (Environment variable: `RESPONSE_CACHE_ENABLED`)

[](#enabled-environment-variable-response_cache_enabled)

Using this setting, you can globally enable or disable the response cache for all requests. If you set it to `false`, nothing will be cached.

Defaults to `true`.

### `ttl` (Environment variable: `RESPONSE_CACHE_TTL`)

[](#ttl-environment-variable-response_cache_ttl)

This setting specifies the amount of time responses will be cached before being marked as stale. The value must be specified in seconds.

Defaults to `60 * 60 * 24`, or exactly 24 hours.

### `store` (Environment variable: `RESPONSE_CACHE_STORE`)

[](#store-environment-variable-response_cache_store)

Here you may pass any cache store defined in your `config/cache.php` file. Please note that not all stores support tagging: For better control over and increased performance of your cache, we strongly recommend using a store with tag support, like Redis or APC.

Defaults to `file`.

### `tags` (Environment variable: `RESPONSE_CACHE_TAGS`)

[](#tags-environment-variable-response_cache_tags)

If your store supports tags, all responses cached will also be tagged with these tags by default. Additional tags may be used depending on the middleware and strategy.

Defaults to `[]`.

### `server_timing` (Environment variable: `RESPONSE_CACHE_SERVER_TIMING`)

[](#server_timing-environment-variable-response_cache_server_timing)

If the server timing option is enabled, a Server-Timing header containing the initial caching time will be added to all cached responses. This makes debugging easier. Leaving it enabled in production probably has no negative consequences aside from a small performance penalty due to the bigger response size.

Defaults to `false`.

### `cache_status_enabled` (Environment variable: `RESPONSE_CACHE_STATUS_ENABLED`)

[](#cache_status_enabled-environment-variable-response_cache_status_enabled)

If the cache status option is enabled, a `Response-Cache-Status` header containing the cache status (`hit` or `miss`) will be added to all responses. This makes debugging easier.

Defaults to `true`.

Usage
-----

[](#usage)

After following the installation instructions above, you should be ready to go: Responses with a status code in the `200` and `300` range will be cached and returned on subsequent visits. To bypass the cache for specific routes, you can simply add the `bypass_cache` middleware:

```
Route::get('/kitten')->middleware('bypass_cache');
```

### Flushing the cache manually

[](#flushing-the-cache-manually)

To clear the cache manually, you can use the `response-cache:flush` artisan command:

```
php artisan response-cache:flush
```

This will flush the entire response cache. To delete a given set of cache tags only, add them to the command:

```
php artisan response-cache:flush tag-1 tag-2 ... tag-n
```

### Flushing the cache programmatically

[](#flushing-the-cache-programmatically)

In production use, it is often helpful to flush the cache automatically if something happens. For example, you can flush the cache whenever a model event is fired by setting up an observer:

```
use Matchory\ResponseCache\Facades\ResponseCache;

class ExampleObserver {
    public function saved(): void {
        ResponseCache::clear();
    }

    public function deleted(): void {
        // By passing one or more tags, only those items tagged appropriately
        // will be cleared
        ResponseCache::clear(['example']);
    }
}
```

By invoking the `clear` method, the entire store (for the given tags) will be purged. To be more selective, use the `delete` method:

```
use Matchory\ResponseCache\Facades\ResponseCache;

ResponseCache::delete('/example/url');
ResponseCache::delete(['/example/1', '/example/2']);
```

> **Note:** This will not work for cache items that require context information, such as user authentication. If you hit this problem, you'll probably want to work with tags instead.

#### Cache Tags

[](#cache-tags)

Cache tags are a simple, yet very powerful mechanism for efficient cache usage. By applying tags to a set of cached items, you can purge all of them, without ever knowing the individual cache keys of these items. Say, there are lots of cached data points all related to "flights": plane schedules, arrival dates, passenger records, etc. All is fine and well, until a flight is cancelled! Now, we will need to purge the cache for anything that includes the flight in question. This would be a logical nightmare, hadn't we set up cache tags: Instead of deleting lots of items manually, we instruct Laravel to purge all items tagged with the flight number, and we're good to go!

This library is built heavily around the concept of cache tags: By tagging properly, you can make granular cache flushing a breeze. Tags can be added to routes using several approaches:

- By passing them to the middleware: ```
    Route::get('/foo')->middleware(['cache:tag-1,tag-2']);
    ```
- By adding them to the `config/response-cache.php` config file: ```
    'tags' => env('RESPONSE_CACHE_TAGS', [ 'tag-1', 'tag-2' ]),
    ```
- By returning them from [your strategy](#customizing-tagging).

#### Using bindings in cache tags

[](#using-bindings-in-cache-tags)

This library supports adding dynamic tags that are based on route bindings. This works pretty much the same as with ordinary route bindings, but with the added benefit of also having access to all request values, not just those mentioned in the route itself.
To add a binding to your cache tag, simply include the name of a parameter in curly braces: `flights.{flight}`. As soon as something is to be fetched from or put into the cache, this binding will be resolved using the current request instance. If the parameter `flight` was an instance of an Eloquent model, it would be replaced with its route key name, so probably the flight ID!

Take a look at the following example:

```
Route::get('/api/v{version}/flights/{flight}', function(\App\Flight $flight) {
    // ...
})->middleware('cache:api.v{version},flights,flights.v{version},flights.{flight},flights.v{version}.{flight}');
```

Imagine we perform the following request: `/api/v3/flights/505`
Now, the response generated by this route would be tagged with the following tags:

- `api.v3`
- `flights`
- `flights.v3`
- `flights.505`
- `flights.v3.505`

Depending on your requirements, you can simply flush the cache for any of these and rest assured the response will be invalidated!

### Caching Strategies

[](#caching-strategies)

A *strategy* is what the response cache uses to determine just how a response should be cached. It generates cache keys, determines cache tags and controls cache bypassing. The default strategy should fit for most use cases, but if it doesn't, we got you covered, too!

To use a custom strategy, start by either extending [the default implementation](./src/Support/BaseStrategy.php) (recommended) or implementing [the `CacheStrategy` interface](./src/Contracts/CacheStrategy.php).

#### Customize cache keys

[](#customize-cache-keys)

To customize the way cache keys are generated, you have several options, as the default implementation splits this process in multiple methods:

```
use Illuminate\Http\Request;use Matchory\ResponseCache\Support\BaseStrategy;

class MyStrategy extends BaseStrategy
{
    public function key(Request $request): string
    {
        $identifier = $this->extractRequestIdentifier($request);
        $suffix = $this->buildSuffix($request);

        return $this->hash($identifier . $suffix);
    }
}
```

- The `extractRequestIdentifier` method extracts the full request URL and method as the base of the cache key. This should be enough in most applications.
- The `buildSuffix` method checks for the current authentication status and appends the ID of the authenticated user. You may wish to modify this to use a customer or application identifier, for example.
- The `hash` method builds a hash of the given cache key (by default it uses `md5`), so the key length stays consistent.

#### Customizing cache bypass

[](#customizing-cache-bypass)

To customize whether a response is cached or not, you can implement one or more helpers:

```
use Illuminate\Http\Request;
use Matchory\ResponseCache\Support\BaseStrategy;
use Symfony\Component\HttpFoundation\Response;

class MyStrategy extends BaseStrategy
{
    public function shouldCache(Request $request, Response $response): bool
    {
        if (! $this->isMethodCachable($request)) {
            return false;
        }

        return $this->isSuccessful($response);
    }
}
```

By default, this will cache any request with the `GET` or `HEAD` methods, and responses with a success or redirection status.

#### Customizing tagging

[](#customizing-tagging)

Tagging cached responses is an immensely powerful feature that allows you to flush a collection of cache entries if something happens. So if a single member of a collection is deleted, for example, you can remove all cached instances of the same collection, without having to know the exact cache keys used to retrieve them!
To make this as easy as possible, strategies provide a method to pull tags from a request and response:

```
use Illuminate\Http\Request;
use Matchory\ResponseCache\Support\BaseStrategy;
use Symfony\Component\HttpFoundation\Response;

class MyStrategy extends BaseStrategy
{
    public function tags(Request $request, Response|null $response = null): array
    {
        return [
            $request->attributes->get('customer.id')
        ];
    }
}
```

### Using the `ResponseCache` middleware manually

[](#using-the-responsecache-middleware-manually)

Instead of simply adding the caching middleware to all web routes as shown above, you can of course also add it to selected routes manually. In this case, you also have the possibility to configure the time to leave and add a set of tags per route:

```
// Default settings as set in the config file
Route::get('/foo')->middleware('response_cache')

// TTL of 60 seconds
Route::get('/bar')->middleware('response_cache:60');

// Tags "foo", "bar" and "baz" are added
Route::get('/baz')->middleware('response_cache:foo,bar,baz');

// TTL of 60 seconds and tags "foo", "bar" and "baz" are added
Route::get('/quz')->middleware('response_cache:60,foo,bar,baz');
```

If the first parameter to the middleware is a number, it will be interpreted as a TTL value, everything that follows as tags. The TTL will override the [configuration value](#ttl-environment-variable-response_cache_ttl), tags will be merged.

### Reacting to cache events

[](#reacting-to-cache-events)

This library exposes some events you can listen for and act accordingly. This is probably most helpful during [debugging](#debugging).

#### `Hit`

[](#hit)

Emitted if a response was found in the cache. Includes the request instance.

#### `Miss`

[](#miss)

Emitted if a response could not be found in the cache or was [indicated as non-cachable by the caching strategy](#caching-strategies) and thus had to be generated by the application. Includes the request instance.

#### `Flush`

[](#flush)

Emitted if the cache was flushed. Includes the tags that were flushed, or `null` if all tags were flushed.

### Manual response serialization

[](#manual-response-serialization)

By default, the response cache uses a [cache repository implementation](./src/Repository.php) with a very simple serialization method: *Doing nothing*. Any serialization is deferred to Laravel's cache implementation. In rare cases, you may need to change this behavior and modify a response before serializing or after hydrating it.
To do so, start by extending the `Repository` class:

```
use Matchory\ResponseCache\Repository;
use Symfony\Component\HttpFoundation\Response;

class CustomRepository extends Repository
{
    protected function serialize(Response $response) : mixed
    {
        return serialize($response);
    }

    protected function hydrate(mixed $responseData): Response
    {
        return unserialize($responseData, [Response::class])
    }
}
```

Override the container binding in your `AppServiceProvider`, so your repository will be used instead of the default:

```
use Matchory\ResponseCache\Repository;

protected function register():void
    {
        $this->app->bind(Repository::class, CustomRepository::class);
    }
```

### Debugging

[](#debugging)

Cache issues can be a little annoying to debug. This library has several facilities built in to make the process as simple as possible:

1. **Enable the `Server-Timing` header**: By switching this feature on, all responses will include a [`Server-Timing` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) that includes the time your response was cached. This information will automatically show up in your browser's developer tools!
2. **Listen to cache events**: By listening to [the cache events](#reacting-to-cache-events), you can make sure everything is working as intended.
3. **Temporarily or conditionally disable caching**: By changing the `response-cache.enabled` setting, you can quickly determine whether caching is the culprit.
4. **Use a custom repository**: [Override the built-in serialization method](#manual-response-serialization) to take control of response serialization and hydration.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance45

Moderate activity, may be stable

Popularity30

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~80 days

Recently: every ~65 days

Total

19

Last Release

433d ago

Major Versions

0.1.0 → 1.0.02021-03-31

### Community

Maintainers

![](https://www.gravatar.com/avatar/aa633f25468b1a85e85646d55aa16c39d04e163e92744d0a7c2a694dbcafc3e1?d=identicon)[Radiergummi](/maintainers/Radiergummi)

---

Top Contributors

[![Radiergummi](https://avatars.githubusercontent.com/u/6115429?v=4)](https://github.com/Radiergummi "Radiergummi (45 commits)")

---

Tags

cachinglaravellaravel-packageperformancephpphp8

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/matchory-response-cache/health.svg)

```
[![Health](https://phpackages.com/badges/matchory-response-cache/health.svg)](https://phpackages.com/packages/matchory-response-cache)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[genealabs/laravel-model-caching

Automatic caching for Eloquent models.

2.4k4.8M26](/packages/genealabs-laravel-model-caching)[mikebronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k127.1k1](/packages/mikebronner-laravel-model-caching)[illuminate/cache

The Illuminate Cache package.

12835.6M1.4k](/packages/illuminate-cache)[laragear/cache-query

Remember your query results using only one method. Yes, only one.

272122.8k](/packages/laragear-cache-query)[namoshek/laravel-redis-sentinel

An extension of Laravels Redis driver which supports connecting to a Redis master through Redis Sentinel.

38679.0k](/packages/namoshek-laravel-redis-sentinel)

PHPackages © 2026

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