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

ActiveLibrary[Caching](/categories/caching)

angelleger/laravel-response-cache
=================================

Production-grade response caching for Laravel APIs with ETag, Redis tags, per-route TTLs, and safe auth-variation

v1.0.7(8mo ago)0484↓50%[1 PRs](https://github.com/angelleger/laravel-response-cache/pulls)MITPHPPHP ^8.1CI passing

Since Aug 29Pushed 8mo agoCompare

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

READMEChangelog (7)Dependencies (11)Versions (13)Used By (0)

Laravel Response Cache
======================

[](#laravel-response-cache)

Key-based full response caching for Laravel 10+ applications. The package stores complete GET/HEAD responses in the configured cache store using deterministic keys. It offers a small helper API, middleware, and artisan commands for managing cached responses without relying on cache tags.

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

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.x

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

[](#installation)

```
composer require angelleger/laravel-response-cache
php artisan vendor:publish --tag=response-cache-config
```

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

[](#configuration)

`config/response_cache.php`

```
return [
    'ttl' => 300, // default lifetime in seconds
    'store' => env('RESPONSE_CACHE_STORE'), // cache store to use
    'key_prefix' => 'resp_cache:', // prefix for all keys and indexes
    'guest_only' => true, // only cache guests unless auth=true is passed to middleware
    'vary_on_headers' => ['Accept', 'Accept-Language'], // headers included in the key
    'vary_on_cookies' => [], // cookies included in the key
    'include_query_params' => [], // when set, only these query parameters are used
    'ignore_query_params' => ['_', 'utm_*'], // query parameters to ignore (supports * suffix)
    'status_whitelist' => [200], // only cache these response codes
    'max_payload_kb' => null, // skip responses larger than this (in kilobytes)
    'etag' => true, // automatically add ETag header to cached responses
    'lock_seconds' => 0, // hold an atomic lock for this many seconds while generating
    'lock_wait' => 10, // seconds to wait for a lock to be released
    'debug' => env('RESPONSE_CACHE_DEBUG', false), // enable debug helpers
];
```

### Configuration Notes

[](#configuration-notes)

- **ttl**: default time-to-live for cached responses when no explicit value is supplied.
- **store**: cache store to use; `null` uses the application's default store.
- **key\_prefix**: string prepended to every cache key and route index entry.
- **guest\_only**: when `true`, authenticated users are skipped unless the middleware parameter `auth=true` is provided.
- **vary\_on\_headers / vary\_on\_cookies**: header and cookie names that should contribute to the cache key.
- **include\_query\_params**: if non-empty, only these query parameters are considered when building the key.
- **ignore\_query\_params**: query parameters to discard; supports a trailing `*` wildcard.
- **status\_whitelist**: response status codes eligible for caching.
- **max\_payload\_kb**: maximum size of the response body; larger responses are bypassed.
- **etag**: toggle automatic generation of an `ETag` header when caching.
- **lock\_seconds / lock\_wait**: when `lock_seconds` &gt; 0, generation is wrapped in an atomic lock to prevent cache stampedes.
- **debug**: when enabled, exposes additional debug headers.

Cache Key Strategy
------------------

[](#cache-key-strategy)

Keys follow the pattern:

```
{method}:{path-or-route}:{normalized-query}:{locale}:{guard-or-guest}

```

The query segment is created by sorting parameters, removing ignored keys, and injecting `vary_on_headers`/`vary_on_cookies` values as pseudo parameters (`h_header` / `c_cookie`). The active authentication guard name (or `guest`) and the request locale are appended to avoid collisions.

Middleware
----------

[](#middleware)

Apply the `resp.cache` middleware to any GET/HEAD route that should be cached.

```
Route::get('/posts', fn () => Post::all())
    ->middleware('resp.cache:ttl=120');

// Allow authenticated users to be cached
Route::get('/dashboard', fn () => view('dashboard'))
    ->middleware('auth', 'resp.cache:ttl=60,auth=true');
```

### Middleware Parameters

[](#middleware-parameters)

- `ttl=` – override the default TTL for this route.
- `auth=true` – cache authenticated responses even if `guest_only` is enabled.

Responses are cached only when:

- The HTTP method is GET or HEAD.
- The response status code appears in `status_whitelist`.
- The response size does not exceed `max_payload_kb` (when set).
- The request does not contain `Cache-Control: no-store`.

Cached responses include an `X-Cache: HIT` header for debugging. You can disable caching on a per-request basis by sending `Cache-Control: no-store` from the client or controller.

Helper API
----------

[](#helper-api)

```
use AngelLeger\ResponseCache\Facades\ResponseCache;

$key = ResponseCache::makeKey(request());
$response = ResponseCache::rememberResponse(request(), fn () => response('ok'), 60);
ResponseCache::forgetByKey($key);
ResponseCache::forgetRoute('posts.index');
```

- **makeKey(Request $request, array $overrides = \[\])** – build the cache key used for the request.
- **rememberResponse(Request $request, Closure $callback, DateTimeInterface|int $ttl)** – return the cached response or execute the callback and store the result.
- **forgetByKey(string $key)** – remove a cached response.
- **forgetRoute(string $routeName)** – remove all cached responses for the route (uses a bounded key index, max 1000 entries).

Artisan Commands
----------------

[](#artisan-commands)

```
php artisan response-cache:clear --key="get:posts::en:guest"
php artisan response-cache:clear --route=posts.index
php artisan response-cache:stats
```

- **response-cache:clear** – clear by exact key or by route name (uses the internal index).
- **response-cache:stats** – show basic cache information such as the underlying driver.

Caveats
-------

[](#caveats)

- The package uses key-based invalidation only; cache `flush()` is intentionally avoided because it clears unrelated data.
- Streamed responses or those not meeting cache rules (status, size, etc.) are skipped automatically.
- Route indexes are capped to the most recent 1000 keys to remain memory safe.
- Use caution when changing configuration in production; mismatched prefixes or stores can orphan keys.

License
-------

[](#license)

MIT

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance61

Regular maintenance activity

Popularity17

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 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 ~1 days

Total

7

Last Release

250d ago

### Community

Maintainers

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

---

Top Contributors

[![angelleger](https://avatars.githubusercontent.com/u/8051940?v=4)](https://github.com/angelleger "angelleger (25 commits)")

---

Tags

cacheetaglaravelmiddlewareredisresponseresponsemiddlewareapilaravelperformancerediscacheEtag

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[anahkiasen/flatten

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

33313.0k](/packages/anahkiasen-flatten)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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