PHPackages                             dragon-code/laravel-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. dragon-code/laravel-cache

ActiveLibrary[Caching](/categories/caching)

dragon-code/laravel-cache
=========================

An improved interface for working with cache

4.2.0(2mo ago)6844.8k↓32.6%38MITPHPPHP ^8.2CI passing

Since Feb 1Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/TheDragonCode/laravel-cache)[ Packagist](https://packagist.org/packages/dragon-code/laravel-cache)[ Fund](https://boosty.to/dragon-code)[ Fund](https://yoomoney.ru/to/410012608840929)[ RSS](/packages/dragon-code-laravel-cache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (12)Versions (51)Used By (8)

Smart Cache for Laravel
=======================

[](#smart-cache-for-laravel)

  ![Smart Cache](https://camo.githubusercontent.com/3456ce2bcc0fc936a3609a6b73ed920010f28b7b6098c1aded75684fc67a8b82/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f536d61727425323043616368652e706e673f7061747465726e3d746f706f677261706879267374796c653d7374796c655f3226666f6e7453697a653d3130307078266d643d312673686f7757617465726d61726b3d31267468656d653d6c69676874267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d647261676f6e2d636f64652532466c61726176656c2d6361636865266465736372697074696f6e3d416e2b696d70726f7665642b696e746572666163652b666f722b776f726b696e672b776974682b636163686526696d616765733d68747470732533412532462532466c61726176656c2e636f6d253246696d672532466c6f676f6d61726b2e6d696e2e737667)[![Stable Version](https://camo.githubusercontent.com/3e9036e2328bd55f6e09ada5b725540243b50af3e08d5631dd7c436fda6cf378/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f546865447261676f6e436f64652f6c61726176656c2d63616368653f6c6162656c3d737461626c65267374796c653d666c61742d737175617265)](https://packagist.org/packages/dragon-code/laravel-cache)[![Total Downloads](https://camo.githubusercontent.com/6e47629f33bd7d84eada5482629638ce71b3de13a12fba54b83bce297c21ff6f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f647261676f6e2d636f64652f6c61726176656c2d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dragon-code/laravel-cache)[![Github Workflow Status](https://camo.githubusercontent.com/a335af94b46d12e9cb59118dcfff19cee6c10de76691341cbe51162bdd266ee6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f546865447261676f6e436f64652f6c61726176656c2d63616368652f706870756e69742e796d6c3f7374796c653d666c61742d737175617265)](https://github.com/TheDragonCode/laravel-cache/actions)[![License](https://camo.githubusercontent.com/bd135f9a5326bdf2f552f29e3fa4a5209d0c2178ab768b4ddd59bb7f82e77423/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f546865447261676f6e436f64652f6c61726176656c2d63616368652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

Note

The `Cache::tags()` method in Laravel 11 is not compatible with PHP 8.5.

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

[](#installation)

To get the latest version of `Smart Cache`, simply require the project using [Composer](https://getcomposer.org):

```
composer require dragon-code/laravel-cache
```

Or manually update `require` block of `composer.json` and run `composer update`.

```
{
    "require": {
        "dragon-code/laravel-cache": "^4.0"
    }
}
```

Upgrade Guide
-------------

[](#upgrade-guide)

Information on upgrade from version 3 to 4 is located in the [UPGRADE](UPGRADE.md) file.

Using
-----

[](#using)

### Keys And Tags

[](#keys-and-tags)

In addition to passing an explicit value, you can also pass objects and arrays to the `keys` and `tags` methods.

For example:

```
use DragonCode\Cache\Services\Cache;
use Tests\Fixtures\Dto\DtoObject;
use Tests\Fixtures\Simple\CustomObject;

$arr1 = ['foo', 'bar'];
$arr2 = new ArrayObject(['foo', 'bar']);
$arr3 = DtoObject::make(['foo' => 'Foo', 'bar'=> 'Bar']);
$arr4 = new CustomObject();

Cache::make()->key($arr1)->tags($arr1);
Cache::make()->key($arr2)->tags($arr3);
Cache::make()->key($arr2)->tags($arr3);
Cache::make()->key($arr4)->tags($arr4);

Cache::make()
    ->key([$arr1, $arr2, $arr3, $arr4, 'foo', 'bar'])
    ->tags([$arr1, $arr2, $arr3, $arr4, 'foo', 'bar']);
```

Unpacking and processing of objects occurs as follows:

```
use DragonCode\Cache\Services\Cache;
use Tests\Fixtures\Dto\DtoObject;
use Tests\Fixtures\Simple\CustomObject;

['Foo', 'Bar'];
// as key: ['Foo', 'Bar']
// as tag: ['foo', 'bar']

new ArrayObject(['Foo', 'Bar']);
// as key: ['Foo', 'Bar']
// as tag: ['foo', 'bar']

DtoObject::make(['foo' => 'Foo', 'bar'=> 'Bar']);
// as key: ['Foo', 'Bar']
// as tag: ['foo', 'bar']

new CustomObject();
// as key: ['Foo']
// as tag: ['foo']
```

#### Keys Handling

[](#keys-handling)

Since the main problem of working with the cache's key compilation, this package solves it.

By passing values to the `keys` method, we get a ready-made key at the output.

The hash is formed by the value `key=value`, which allows avoiding collisions when passing identical objects.

In the case of passing nested arrays, the key is formed according to the principle `key1.key2=value`, where `key1`and `key2` are the keys of each nested array.

For example:

```
use DragonCode\Cache\Services\Cache;

Cache::make()->key('foo', 'bar', [null, 'baz', 'baq']);

// Key is `d76f2bde023f5602ae837d01f4ec1876:660a13c00e04c0d3ffb4dbf02a84a07a:6fc3659bd986e86534c6587caf5f431a:bd62cbee62e027d0be4b1656781edcbf`
```

This means that when writing to the cache, the tree view will be used.

For example:

```
use DragonCode\Cache\Services\Cache;

Cache::make()->key('foo', 'foo')->put('Foo');
Cache::make()->key('foo', 'bar')->put('Bar');
Cache::make()->key('baz')->put('Baz');

// d76f2bde023f5602ae837d01f4ec1876:
//     086f76c144511e1198c29a261e87ca50: Foo
//     660a13c00e04c0d3ffb4dbf02a84a07a: Bar
// 1b9829f3bd21835a15735f3a65cc75e9: Baz
```

#### Disable key hashing

[](#disable-key-hashing)

In some cases, you need to disable the use of the key hashing mechanism. To do this, simply call the `hashKey(false)` method:

```
use DragonCode\Cache\Services\Cache;

Cache::make()->key('foo', 'foo')->hashKey(false)->put('Foo');
Cache::make()->key('foo', 'bar')->hashKey(false)->put('Bar');
Cache::make()->key('baz')->hashKey(false)->put('Baz');

// 0=foo:
//     1=foo: Foo
//     1=bar: Bar
// 0=baz: Baz
```

```
use DragonCode\Cache\Services\Cache;

Cache::make()->key([
            ['foo' => 'Foo'],
            ['bar' => 'Bar'],
            [['Baz', 'Qwerty']],
])->hashKey(false)->put('Baz');

// 0.foo=Foo:1.bar=Bar:2.0.0=Baz:2.0.1=Qwerty
```

### With Authentication

[](#with-authentication)

In some cases, it is necessary to bind the cache to certain users. To do this, we have added the `withAuth` helper.

```
use DragonCode\Cache\Services\Cache;
use Illuminate\Support\Facades\Auth;

Cache::make()->withAuth()->key('foo', 'bar');

// instead of
Cache::make()->key(get_class(Auth::user()), Auth::id(), 'foo', 'bar');
```

When processing requests with a call to the withAuth method, the binding will be carried out not only by identifier, but also by reference to the model class, since a project can have several models with the possibility of authorization.

For example, `App\Models\Employee`, `App\Models\User`.

### When Enabled

[](#when-enabled)

#### Basic

[](#basic)

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()
    ->key('foo', 'bar', ['baz', 'baq'])
    ->ttl(200, true);
    // When `true` is equal to 200 minutes.
    // When `false` is equal to 200 seconds.
    // By default, `true`

$cache->put(static fn() => 'Some value');
// or
$cache->put('Some value');
// Contains cached `Some value`

$cache->remember(static fn() => 'Some value');
// or
$cache->remember('Some value');
// Contains cached `Some value`

$cache->rememberForever(static fn() => 'Some value');
// or
$cache->rememberForever('Some value');
// Contains cached `Some value`

// Uses the functionality of the `Cache::flexible()` method
$cache->flexible(50)->remember('Some value');
// equals `Cache::flexible($key, [50, 200], fn () => 'Some value')`

$cache->flexible(-50)->remember('Some value');
// equals `Cache::flexible($key, [150, 200], fn () => 'Some value')`

$cache->flexible(0)->remember('Some value'); // By default, `0`
// equals `Cache::flexible($key, [170, 200], fn () => 'Some value')`
// (200 - 15%) = 170

$cache->flexible(50, true); // 50 minutes
$cache->flexible(50, false); // 50 seconds
$cache->flexible(0, false); // the `true/false` modifier is not used

$cache->get();
// Returns cached `Some value`

$cache->has();
// Returns `true`

$cache->doesntHave();
// Returns `false`

$cache->forget();
// Will remove the key from the cache.

$cache->flush();
// Clears keys or tags by value
```

```
use DragonCode\Cache\Services\Cache;
use App\Models\User;

$user = User::first();

$cache = Cache::make()->key('foo');

$cache->put(static fn() => $user);
// or
$cache->put($user);
// Contains cached `$user`

$cache->remember(static fn() => $user);
// or
$cache->remember($user);
// Contains cached `$user`

$cache->rememberForever(static fn() => $user);
// or
$cache->rememberForever($user);
// Contains cached `$user`

$cache->flexible()->remember($user);
// Returns User model with flexibility

$cache->get();
// Returns User model

$cache->has();
// Returns `true`

$cache->doesntHave();
// Returns `false`

$cache->forget();
// Will remove the key from the cache.

$cache->flush();
// Clears keys or tags by value
```

#### Method Call Chain

[](#method-call-chain)

Sometimes in the process of working with a cache, it becomes necessary to call some code between certain actions, and in this case the `call` method will come to the rescue:

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()->key('foo');
$warmUp = false;

$cache
    ->call(fn (Cache $cache) => $cache->forget(), $warmUp)
    ->call(fn () => $someService->someMethod())
    ->remember('foo');
```

In addition, the `forget` method now returns an instance of the `Cache` object, so it can be used like this:

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()->key('foo');

$cache
    ->forget()
    ->call(fn () => $someService->someMethod())
    ->remember('foo');
```

Previously, you had to use the following sequence:

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()->key('foo');
$warmUp = false;

if ($warmUp) {
    $cache->forget();
}

$someService->someMethod()

$cache->remember('foo');
```

#### Custom TTL

[](#custom-ttl)

By default, the cache will be written for 1 day.

The cache will be written for the specified number of minutes, seconds or the `DateTimeInterface` instance.

It does not matter in which direction the time shift will be. During processing, the value is converted to the `abs()`.

##### As Minutes

[](#as-minutes)

```
use Carbon\Carbon;
use DateTime;
use DragonCode\Cache\Services\Cache;
use DragonCode\Cache\Support\Ttl;

Cache::make()->ttl(10);
Cache::make()->ttl('10');
Cache::make()->ttl(fn () => 10);

Cache::make()->ttl(Carbon::now()->addDay());
Cache::make()->ttl(new DateTime('tomorrow'));
```

##### As Seconds

[](#as-seconds)

```
use Carbon\Carbon;
use DateTime;
use DragonCode\Cache\Services\Cache;

Cache::make()->ttl(10, false);
Cache::make()->ttl('10', false);
Cache::make()->ttl(fn () => 10, false);

Cache::make()->ttl(Carbon::now()->addDay(), false);
Cache::make()->ttl(new DateTime('tomorrow'), false);
```

##### By Objects And Custom Strings

[](#by-objects-and-custom-strings)

You can also store all TTL values in one place - in the `config/cache.php` file.

To do this, add a `ttl` block to the file and [`define`](config/cache.php) a TTL for the objects.

After that you can use the following construction:

```
use DragonCode\Cache\Services\Cache;
use Tests\Fixtures\Simple\CustomObject;

Cache::make()->ttl(CustomObject::class);
Cache::make()->ttl(new CustomObject());
Cache::make()->ttl('custom_key');
Cache::make()->ttl((object) ['foo' => 'Foo']);

// You can also specify that these values are in seconds, not minutes:
Cache::make()->ttl(CustomObject::class, false);
Cache::make()->ttl(new CustomObject(), false);
Cache::make()->ttl('custom_key', false);
Cache::make()->ttl((object) ['foo' => 'Foo'], false);
```

If the value is not found, the [default value](config/cache.php) will be taken, which you can also override in the [configuration file](config/cache.php).

#### Tagged

[](#tagged)

For repositories that support tagging, the keys will be saved separated by tags.

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()
    ->tags('actor', 'author')
    ->key('foo', 'bar', ['baz', 'baq']);

$cache->put(static fn() => 'Some value');
// or
$cache->put('Some value');
// Contains cached `Some value`

$cache->get();
// Returns cached `Some value`

$cache->has();
// Returns `true`

$cache->doesntHave();
// Returns `false`

$cache->forget();
// Will remove the key from the cache.

$cache->flush();
// Clears keys or tags by value
```

To retrieve a tagged cache item, pass the same ordered list of tags to the tags method and then call the get method with the key you wish to retrieve:

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()->key('foo', 'bar');

$cache->tags('actor', 'author')->put(static fn() => 'Some value');
// or
$cache->tags('actor', 'author')->put('Some value');
// Contains cached `Some value`

$cache->tags('actor', 'author')->get();
// Returns cached `Some value`

$cache->tags('actor')->get();
// Returns `null`

$cache->tags('author')->get();
// Returns `null`

$cache->tags('author')->flush();
// Clears keys or tags by value
```

> See the official Laravel [documentation](https://laravel.com/docs/cache#accessing-tagged-cache-items).

### When Disabled

[](#when-disabled)

Passing `when = false` will not write to the cache.

```
use DragonCode\Cache\Services\Cache;

$cache = Cache::make()
    ->when(false)
    ->key('foo', 'bar');

$value = $cache->put(static fn() => 'Some value');
// or
$value = $cache->put('Some value');
// Returns `Some value`

$cache->get();
// Returns `null`

$cache->has();
// Returns `false`

$cache->doesntHave();
// Returns `true`
```

You can also define whether to enable or disable the use of cache storage in the settings.

For example:

```
// config/cache.php
return [
    'enabled' => [
        // App\Models\Page::class     => true,
        //
        // 'stdClass' => false,
        //
        // 'foo' => false,
    ],
];
```

```
use App\Services\Some;use DragonCode\Cache\Services\Cache;

// as string
$cache = Cache::make()->when('foo');

// as class-string
$cache = Cache::make()->when(Some::class);
$cache = Cache::make()->when(static::class);
$cache = Cache::make()->when(self::class);

// as class
$cache = Cache::make()->when(new Some);
$cache = Cache::make()->when($this);

// as stdClass
$cache = Cache::make()->when((object)['foo' => 'Foo']);
```

License
-------

[](#license)

This package's licensed under the [MIT License](LICENSE).

###  Health Score

64

—

FairBetter than 99% of packages

Maintenance88

Actively maintained with recent releases

Popularity41

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity89

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 64.9% 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 ~63 days

Recently: every ~110 days

Total

48

Last Release

61d ago

Major Versions

1.x-dev → v2.0.02021-11-13

2.x-dev → v3.0.02022-04-20

3.x-dev → 4.0.02025-02-21

PHP version history (6 changes)1.0.0PHP ~5.6|^7.0

v2.0.0PHP ^7.3|^8.0

v2.5.0PHP ^7.3 || ^8.0

v3.0.0PHP  ^8.0

v3.1.0PHP ^8.0

4.0.0PHP ^8.2

### Community

Maintainers

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

---

Top Contributors

[![andrey-helldar](https://avatars.githubusercontent.com/u/10347617?v=4)](https://github.com/andrey-helldar "andrey-helldar (135 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (35 commits)")[![actions-user](https://avatars.githubusercontent.com/u/65916846?v=4)](https://github.com/actions-user "actions-user (34 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (4 commits)")

---

Tags

cachehelperlaravellaravel-packagephplaravelhelpercachedragondragon codeandrey helldar

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dragon-code-laravel-cache/health.svg)

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

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[dragon-code/pretty-routes

Pretty Routes for Laravel

10058.7k4](/packages/dragon-code-pretty-routes)[dragon-code/laravel-http-logger

Logging incoming HTTP requests

319.8k3](/packages/dragon-code-laravel-http-logger)[dragon-code/migrate-db

Easy data transfer from one database to another

15717.4k](/packages/dragon-code-migrate-db)[dragon-code/laravel-deploy-operations

Performing any actions during the deployment process

240173.5k2](/packages/dragon-code-laravel-deploy-operations)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)

PHPackages © 2026

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