PHPackages                             iksaku/laravel-swr-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. iksaku/laravel-swr-cache

ActiveLibrary[Caching](/categories/caching)

iksaku/laravel-swr-cache
========================

This is my package laravel-swr-cache

1.0.2(2y ago)79.5k↓33.3%[1 PRs](https://github.com/iksaku/laravel-swr-cache/pulls)MITPHPPHP ^8.1

Since Sep 13Pushed 2y ago1 watchersCompare

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

READMEChangelog (3)Dependencies (11)Versions (5)Used By (0)

Laravel Cache Stale-While-Revalidate
====================================

[](#laravel-cache-stale-while-revalidate)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e274838fb1b5134812b938af9e810f1a1d75423936de4205eb941122755eade8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696b73616b752f6c61726176656c2d7377722d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iksaku/laravel-swr-cache)[![GitHub Tests Action Status](https://camo.githubusercontent.com/ac951ebcf224e46af01504659c7a8fb0ca51c99918f7d1c1e64d10b2afacd170/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f696b73616b752f6c61726176656c2d7377722d63616368652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/iksaku/laravel-swr-cache/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/22eee827d134dc61c9545687c0bd37f2d302fa133e35d1216ce91fc931a0ea04/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f696b73616b752f6c61726176656c2d7377722d63616368652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/iksaku/laravel-swr-cache/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/2c55a9e5c055991e523a8374b6eda4d24899ca67c0d1b57f959f894fda1f9f99/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696b73616b752f6c61726176656c2d7377722d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iksaku/laravel-swr-cache)

There are applications out there that rely heavily on cache to improve performance, and thanks to Laravel's `cache()->remember()` method, we can easily cache the result of a callback for a given Time-To-Live (`TTL`).

However, there are cases when the callback may take a long time to execute, and we don't want to wait for it to finish before giving a response back to the user.

This is where the [Stale-While-Revalidate](https://web.dev/stale-while-revalidate/)pattern comes in handy. It allows us to return a cached result immediately, and then execute the callback in the background to update the cache for the next request.

How does SWR works under the hood? ```
flowchart TD
    Request[Request key from cache] --> CacheHit{Is the given key available in cache?}

    CacheHit -->|No| FirstTimeProcess[Execute long process]
    FirstTimeProcess --> FirstTimeCache[Cache result]
    FirstTimeCache --> Response

    CacheHit -->|Yes| CacheStale{Is it stale?}
    CacheStale -->|No| ObtainCache[Get fresh value from cache]
    ObtainCache --> Response

    CacheStale --> |Yes| ObtainStaleCache
        ObtainStaleCache[Get stale value from cache] --> Response

        ObtainStaleCache -.- Background
        subgraph Background[After response]
            LongProcess[Execute long process] --> CacheResult[Cache result]
        end

    Response[Return value] --> Continue[/.../]
```

      Loading Installation
------------

[](#installation)

You can install the package via composer:

```
composer require iksaku/laravel-swr-cache
```

Usage
-----

[](#usage)

The `swr()` method is a wrapper around `cache()->remember()` that adds support for the Stale-While-Revalidate pattern using a new Time-To-Stale argument (`TTS`). You can access this method using the `cache()` helper function:

```
$stats = cache()->swr(
    key: 'stats',
    ttl: now()->addHour(),
    tts: now()->addMinutes(15),
    callback: function () {
        // This may take a couple of seconds...
    }
);

// ...
```

Or using the `Cache` facade:

```
$stats = \Illuminate\Support\Facades\Cache::swr(
    key: 'stats',
    ttl: now()->addHour(),
    tts: now()->addMinutes(15),
    callback: function () {
        // This may take a couple of seconds...
    }
);

// ...
```

Like the `remember()` method, if the value is not available in cache, the callback will be executed and the result will be cached for the given Time-To-Live and the corresponding Time-To-Stale will also be stored.

If the value is available and the Time-To-Stale has not passed, the value is considered *fresh* and will be returned immediately. The callback will not be executed.

If the Time-To-Stale has passed, the value is considered *stale*, it will be returned immediately, and the callback will be executed after the response is sent to the user.

Tip

[Mohamed Said](https://twitter.com/themsaid) has a great post on this. Check it out: [Running a task after the response is sent](https://divinglaravel.com/running-a-task-after-the-response-is-sent).

### Queueing the callback execution

[](#queueing-the-callback-execution)

If you prefer to queue the callback execution instead of running it after the response is sent, you can use the `queue` argument:

```
$stats = cache()->swr(
    key: 'stats',
    ttl: now()->addHour(),
    tts: now()->addMinutes(15),
    callback: function () {
        // This may take more than a couple of seconds...
    },
    queue: true
);
```

And, if you want to further customize the queued job, you can pass on a closure that accepts a parameter of type [`Illuminate\Foundation\Bus\PendingClosureDispatch`](https://laravel.com/api/9.x/Illuminate/Foundation/Bus/PendingClosureDispatch.html):

```
use Illuminate/Foundation/Bus/PendingClosureDispatch;

$stats = cache()->swr(
    key: 'stats',
    ttl: now()->addHour(),
    tts: now()->addMinutes(15),
    callback: function () {
        // This may take more than a couple of seconds...
    },
    queue: function (PendingClosureDispatch $job) {
        $job->onQueue('high-priority')
    }
);
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

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

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Jorge González](https://github.com/iksaku)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

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

Total

3

Last Release

786d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/16e6f847fc85f78ca2828648d5c05bbf59a45eece0ef9979f5a16b7c2c930110?d=identicon)[iksaku](/maintainers/iksaku)

---

Top Contributors

[![iksaku](https://avatars.githubusercontent.com/u/4632429?v=4)](https://github.com/iksaku "iksaku (17 commits)")

---

Tags

cachelaravelphpredisstale-while-revalidatelaraveliksakularavel-swr-cache

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/iksaku-laravel-swr-cache/health.svg)

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

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[ryangjchandler/blade-cache-directive

Cache chunks of your Blade markup with ease.

202200.8k2](/packages/ryangjchandler-blade-cache-directive)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[innoge/laravel-policy-soft-cache

This package helps prevent performance problems with frequent Policy calls within your application lifecycle.

2356.9k](/packages/innoge-laravel-policy-soft-cache)[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)[dragon-code/laravel-cache

An improved interface for working with cache

6844.8k10](/packages/dragon-code-laravel-cache)

PHPackages © 2026

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