PHPackages                             eg-mohamed/laravel-http-client-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. eg-mohamed/laravel-http-client-cache

ActiveLibrary

eg-mohamed/laravel-http-client-cache
====================================

Opt-in response caching for Laravel's HTTP client.

00PHPCI passing

Since Jun 9Pushed todayCompare

[ Source](https://github.com/EG-Mohamed/laravel-http-client-cache)[ Packagist](https://packagist.org/packages/eg-mohamed/laravel-http-client-cache)[ RSS](/packages/eg-mohamed-laravel-http-client-cache/feed)WikiDiscussions main Synced today

READMEChangelog (1)DependenciesVersions (1)Used By (0)

 [![Laravel HTTP Client Cache](https://raw.githubusercontent.com/EG-Mohamed/laravel-http-client-cache/main/assets/og.png)](https://raw.githubusercontent.com/EG-Mohamed/laravel-http-client-cache/main/assets/og.png)

 [ ![Latest Version on Packagist](https://camo.githubusercontent.com/0238c3e38d05bb3d2a586ab7a60b4795cf8329e4255d7cb6cf06d04a7356f613/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f65672d6d6f68616d65642f6c61726176656c2d687474702d636c69656e742d63616368653f7374796c653d666c61742d7371756172652663616368655365636f6e64733d333030) ](https://packagist.org/packages/eg-mohamed/laravel-http-client-cache) [ ![Total Downloads](https://camo.githubusercontent.com/0c2ad1fc93f21ff9bd801880376eb6f55ae975310f78b7b68a60b1783d5f78ae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f65672d6d6f68616d65642f6c61726176656c2d687474702d636c69656e742d63616368653f7374796c653d666c61742d7371756172652663616368655365636f6e64733d333030) ](https://packagist.org/packages/eg-mohamed/laravel-http-client-cache) [ ![Code Style](https://camo.githubusercontent.com/7d7101430e07f16e02618b6eef291c3a363edb0ede31b09acfc069266f6efec3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f45472d4d6f68616d65642f6c61726176656c2d687474702d636c69656e742d63616368652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d7371756172652663616368655365636f6e64733d333030) ](https://github.com/EG-Mohamed/laravel-http-client-cache/actions/workflows/fix-php-code-style-issues.yml) [ ![Code Style](https://camo.githubusercontent.com/f8244655f20cb957a8df3e71ee75fa4d28f63ddd2f403cbe562a9eba7a2441a4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f45472d4d6f68616d65642f6c61726176656c2d687474702d636c69656e742d63616368652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265) ](https://github.com/EG-Mohamed/laravel-http-client-cache/actions) [ ![PHP Version Require](https://camo.githubusercontent.com/2a73c50f317726aa752b9dc30a19f88ecf5f6258bebabe6464317670a49fc733/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f65672d6d6f68616d65642f6c61726176656c2d687474702d636c69656e742d63616368652e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/eg-mohamed/laravel-http-client-cache) [ ![License](https://camo.githubusercontent.com/67b8120c530780f726df40f35c0a3658c2b74adf59a9549d6e5b5c77e9f91bd1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f45472d4d6f68616d65642f6c61726176656c2d687474702d636c69656e742d63616368652e7376673f7374796c653d666c61742d737175617265) ](https://github.com/EG-Mohamed/laravel-http-client-cache/blob/main/LICENSE.md)

Opt-in response caching for Laravel's HTTP client. Cache outbound API responses with a single fluent call — without replacing the `Http` facade or touching Laravel core.

```
use Illuminate\Support\Facades\Http;

$response = Http::cache('products-api', 600)
    ->get('https://api.example.com/products');

$response->fromCache(); // false on the first call, true on subsequent calls
```

The cache layer wraps the normal `PendingRequest`, so everything you already use keeps working: `Http::fake()`, headers, query params, JSON payloads, retries, throwing, and the full `Response` API (`body()`, `json()`, `status()`, `header()`, `successful()`, …).

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

[](#installation)

```
composer require eg-mohamed/laravel-http-client-cache
```

The service provider is auto-discovered. Publish the config file if you want to tweak defaults:

```
php artisan vendor:publish --tag="http-client-cache-config"
```

Basic usage
-----------

[](#basic-usage)

Pass a cache key and a TTL (in seconds) to `Http::cache()`, then chain any normal HTTP client method:

```
$response = Http::cache('weather-today', 600)
    ->get('https://api.example.com/weather');

$response->fromCache(); // bool
$response->json();       // works exactly like a normal response
```

By default only **successful** `GET` requests are cached. The first request hits the network; matching requests within the TTL are served from cache without sending another request.

Flexible TTL (stale-while-revalidate)
-------------------------------------

[](#flexible-ttl-stale-while-revalidate)

Pass an array `[$fresh, $stale]` to use Laravel's `Cache::flexible()`. Values are served fresh for `$fresh` seconds, then served stale (and refreshed in the background) up to `$stale`:

```
$response = Http::cache('currency-rates', [60, 300])
    ->get('https://api.example.com/rates');
```

A plain integer, `DateInterval`, or `DateTimeInterface` uses normal `Cache::remember()` behavior.

Caching read-only POST APIs
---------------------------

[](#caching-read-only-post-apis)

Some APIs expose read-only data over `POST` (reports, search, GraphQL). Opt those methods in explicitly — string, array, and enum values are all accepted and normalized to uppercase:

```
$response = Http::cache('erp-report', 600, methods: ['GET', 'POST'])
    ->post('https://legacy-erp.example.com/report', $payload);
```

Non-allowed methods simply bypass the cache and perform a normal request.

Checking `fromCache()`
----------------------

[](#checking-fromcache)

Every response carries a `fromCache()` flag:

```
$response = Http::cache('products-api', 600)->get($url);

if ($response->fromCache()) {
    // served from cache
}
```

Cache store
-----------

[](#cache-store)

Route the cached payload to a specific store:

```
Http::cache('github-releases', 600)
    ->cacheStore('redis')
    ->get('https://api.github.com/repos/laravel/framework/releases');
```

Tags
----

[](#tags)

Tags are applied only when the underlying store supports them (e.g. Redis). With a store that does not support tagging, tags are silently ignored instead of throwing:

```
Http::cache('github-releases', 600)
    ->cacheStore('redis')
    ->cacheTags(['github', 'releases'])
    ->get($url);
```

Conditional caching
-------------------

[](#conditional-caching)

Decide per-response whether the result should be cached:

```
Http::cache('products-api', 600)
    ->cacheWhen(fn ($response) => $response->successful() && $response->json('available'))
    ->get($url);
```

Status-based caching
--------------------

[](#status-based-caching)

Limit caching to specific status codes:

```
Http::cache('products-api', 600)
    ->cacheStatuses([200, 201])
    ->get($url);
```

Disabling cache
---------------

[](#disabling-cache)

Skip the cache for a single request with `dontCache()`:

```
Http::cache('products-api', 600)
    ->dontCache()
    ->get($url);
```

Or disable the package globally via config (`enabled => false`) — every request passes straight through to the network.

Full fluent API
---------------

[](#full-fluent-api)

```
Http::cache('products-api', 600, methods: ['GET'])
    ->cacheStore('redis')
    ->cacheTags(['external-api', 'products'])
    ->cacheKeyPrefix('http-client')
    ->cacheWhen(fn ($response) => $response->successful())
    ->cacheStatuses([200])
    ->cacheMethods(['GET', 'POST'])
    ->get($url);
```

MethodPurpose`cache($key, $ttl = null, $methods = null)`Start a cached request.`cacheStore(?string $store)`Choose the cache store.`cacheTags(array|string $tags)`Tag entries (tag-capable stores only).`cacheKeyPrefix(?string $prefix)`Override the cache key prefix.`cacheWhen(Closure $callback)`Cache only when the callback returns true.`cacheStatuses(array|int|null $statuses)`Cache only these status codes.`cacheMethods(array|string|UnitEnum $methods)`Override cacheable methods.`dontCache()`Bypass the cache for this request.`fromCache()` *(on the response)*Whether the response was served from cache.Configuration
-------------

[](#configuration)

```
return [
    'enabled' => true,                 // Master switch for the package
    'default_store' => null,           // Default cache store (null = app default)
    'key_prefix' => 'http-client-cache',
    'default_methods' => ['GET'],      // Methods cached by default
    'cache_successful_only' => true,   // Only cache 2xx responses
    'cache_statuses' => null,          // Restrict caching to these statuses
    'cache_failed' => false,           // Allow caching failed responses
    'respect_no_store' => false,       // Skip caching when the response sends Cache-Control: no-store/no-cache
    'default_ttl' => null,             // Fallback TTL when none is provided
    'tags' => [],                      // Default tags
    'serialize_headers' => true,       // Persist response headers
];
```

IDE autocompletion
------------------

[](#ide-autocompletion)

`Http::cache()` and `$response->fromCache()` are registered as macros, so editors don't autocomplete them out of the box. This package ships an `ide-helper.php` stub at its root that PhpStorm indexes automatically from `vendor/` — completion for `Http::cache(...)`, `Factory`/`PendingRequest` chaining, and `Response::fromCache()` works with no setup.

If you use [`barryvdh/laravel-ide-helper`](https://github.com/barryvdh/laravel-ide-helper), the macros are registered at boot and picked up automatically when you regenerate the helper:

```
php artisan ide-helper:generate
```

Testing notes
-------------

[](#testing-notes)

`Http::cache()` wraps the real pending request, so `Http::fake()` keeps working. In tests, use the `array` cache store and remember that a cache hit does **not** send another request:

```
Http::fake(['*' => Http::response(['ok' => true], 200)]);

$first = Http::cache('k', 600)->get('https://api.test/a');
$second = Http::cache('k', 600)->get('https://api.test/a');

expect($first->fromCache())->toBeFalse();
expect($second->fromCache())->toBeTrue();

Http::assertSentCount(1);
```

Behavior summary
----------------

[](#behavior-summary)

- Only `GET` is cached by default; opt in to other methods explicitly.
- Only successful (2xx) responses are cached by default; failed responses are not.
- Method names are normalized to uppercase; string, array, and enum values are accepted.
- Array TTL uses `Cache::flexible()`; everything else uses `Cache::remember()`.
- Only a small serializable payload (body, status, reason, headers) is stored — never the full `Response` object.
- Tags are honored only on stores that support them.
- A cache hit never sends a second HTTP request.

License
-------

[](#license)

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

###  Health Score

20

↑

LowBetter than 13% of packages

Maintenance65

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/23424932?v=4)[Mohamed Said](/maintainers/EG-Mohamed)[@EG-Mohamed](https://github.com/EG-Mohamed)

---

Top Contributors

[![EG-Mohamed](https://avatars.githubusercontent.com/u/23424932?v=4)](https://github.com/EG-Mohamed "EG-Mohamed (6 commits)")

---

Tags

api-cacheapi-performancecachecache-flexibledeveloper-toolsetagexternal-apihttp-cachehttp-clientlaravellaravel-http-clientlaravel-packagephprate-limitresponse-cachestale-while-revalidate

### Embed Badge

![Health badge](/badges/eg-mohamed-laravel-http-client-cache/health.svg)

```
[![Health](https://phpackages.com/badges/eg-mohamed-laravel-http-client-cache/health.svg)](https://phpackages.com/packages/eg-mohamed-laravel-http-client-cache)
```

PHPackages © 2026

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