PHPackages                             joshembling/cache-machine - 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. joshembling/cache-machine

ActiveLibrary[Caching](/categories/caching)

joshembling/cache-machine
=========================

CacheMachine allows you to easily 'withdraw' and 'deposit' cache in your Laravel projects.

v1.1.1(2y ago)78[2 PRs](https://github.com/joshembling/cache-machine/pulls)MITPHPPHP ^8.2

Since Jan 21Pushed 1y ago1 watchersCompare

[ Source](https://github.com/joshembling/cache-machine)[ Packagist](https://packagist.org/packages/joshembling/cache-machine)[ Docs](https://github.com/joshembling/cache-machine)[ GitHub Sponsors]()[ RSS](/packages/joshembling-cache-machine/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (12)Versions (7)Used By (0)

Easily manage your Laravel Cache with `CacheMachine`
----------------------------------------------------

[](#easily-manage-your-laravel-cache-with-cachemachine)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1f96194f3e7f63f62495b281e07b54894350f8d33c0ea7dd64ae2b9ef96ee9e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a6f7368656d626c696e672f63616368652d6d616368696e652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/joshembling/cache-machine)[![GitHub Tests Action Status](https://camo.githubusercontent.com/0ee2b5f31704a794ad30c0d7a0a9e57bb86115e812050a067f05c61a3e3fafae/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6f7368656d626c696e672f63616368652d6d616368696e652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/joshembling/cache-machine/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/f59aa3759bd5ee99dfe365031085fb5e160d9eeae7af7c43fb61569fc8953292/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6f7368656d626c696e672f63616368652d6d616368696e652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/joshembling/cache-machine/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/2ae54a9771c0646e05037f225cfa6c5db17d6b32db8eca961b45969583abdf95/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a6f7368656d626c696e672f63616368652d6d616368696e652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/joshembling/cache-machine)

About
-----

[](#about)

`CacheMachine` is a simple, lightweight way of managing cache for your Laravel models. Instead of executing queries, you can 'withdraw' cached data using specific keys and simultaneously 'deposit' (save) new cache entries when needed.

One of the key advantages of CacheMachine is its automatic triggering feature during model save or delete actions. This ensures your cache is always up-to-date without requiring manual intervention. For those who prefer more control, you have the flexibility to force cache updates at your discretion. Once created, the cache persists indefinitely until your model undergoes an update.

CacheMachine is particularly well-suited for various use cases, including articles and blog posts, product and pricing information, select fields, translations, user profiles, images etc.

While CacheMachine is designed around caching model queries, it offers versatility. You can incorporate any data into your cache keys, ensuring they stay current with your model updates.

**Note**: Be mindful - if your models undergo frequent updates, such as every few seconds, it's advisable to configure your own caching methods according to your specific performance requirements.

Compatability
-------------

[](#compatability)

You are free to use any caching provider you want e.g. Redis, DynamoDB. Refer to [Laravel's documentation on caching](https://laravel.com/docs/10.x/cache#configuration) for further assistance.

This package is compatible with Laravel versions 10 and 11 and PHP versions &gt;= 8.2.

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

[](#installation)

You can install the package via composer:

```
composer require joshembling/cache-machine
```

Usage
-----

[](#usage)

To use CacheMachine, the same structure will apply to each of your models.

1. Add the `CacheMachine` trait.

```
use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    // ...
}
```

2. Add the `cacheKeys()` method to your model. This must return an array with a structure of `string => callable`.

```
use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    /**
     * @var array
     */
    public static function cacheKeys(): array
    {
        $keys = [
            // Cache all posts with the eloquent query as the callback
            'all_posts' => fn () => self::all(),
        ];

        return $keys;
    }

    // ...
}
```

3. You may prefer to dynamically refer to your keys as constants or properties within this class.

```
use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    const ALL = 'all_posts';
    const SELECT = 'select_posts';

    /**
     * @var array
     */
    public static function cacheKeys(): array
    {
        $keys = [
             // Cache all posts
            self::ALL => fn () => self::all(),

             // Cache all posts in a key => value format
            self::SELECT => fn () => self::get()->mapWithKeys(
                fn ($type) => [
                    $type->id => $type->title,
                ]
            ),
        ];

        return $keys;
    }

    // ...
}
```

Once you have set up your model, you are able to `withdraw()` your cache. If it doesn't exist, CacheMachine will automatically `deposit` your cache for you when your callback function is valid.

In other words, CacheMachine will fetch from the cache when it exists, or query the database if it doesn't.

```
// You may pass a string to the withdraw method.
Post::withdraw('all_posts');

// Or one of your model's static properties, relating to a key defined in the `cacheKeys()` method.
Post::withdraw(Post::ALL);
```

If you would like to manually save to the cache e.g. you have manually added records to your database without triggering model observers, you may execute the following:

```
Post::forceFetch(Post::ALL)
```

Collections
-----------

[](#collections)

If your callback functions in your `cacheKeys()` return Eloquent queries, you can use any [collection method](https://laravel.com/docs/10.x/collections#available-methods) to filter your results. You will not need to query your database once the parent query is cached.

Here is a simple example of what you could do on a blog site:

```
// Fetch all posts to display on an archive
Post::withdraw('all_posts');

// Display a single blog article
Post::withdraw('all_posts')
    ->firstWhere('id', 2);

// Filter a user search query
Post::withdraw('all_posts')
    ->where('title', 'like', '%Laravel%')
    ->orWhere('published_at', '>', now()->subDays(30))
    ->map(fn ($post) => strtoupper($post->title))
    ->sortDesc();
```

You may wish to enhance your collections even further so you are mitigating any heavy useage of your database. If you want additional features such as pagination, chunks etc. that don't come out of the box with Laravel, I recommend [laravel-collection-macros by Spatie](https://github.com/spatie/laravel-collection-macros/).

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)

- [Josh Embling](https://github.com/joshembling)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance27

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 93.1% 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 ~18 days

Total

4

Last Release

787d ago

PHP version history (2 changes)v1.0.0PHP ^8.1

v1.1.0PHP ^8.2

### Community

Maintainers

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

---

Top Contributors

[![joshembling](https://avatars.githubusercontent.com/u/65712975?v=4)](https://github.com/joshembling "joshembling (27 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

phplaravelcachecachinglaravel-cacheJosh Emblingcache-machine

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/joshembling-cache-machine/health.svg)

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

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[swayok/alternative-laravel-cache

Replacements for Laravel's redis and file cache stores that properly implement tagging idea. Powered by cache pool implementations provided by http://www.php-cache.com/

202541.1k6](/packages/swayok-alternative-laravel-cache)[alekseykorzun/memcached-wrapper-php

Optimized PHP 5 wrapper for Memcached extension that supports dog-piling, igbinary and local storage

2984.6k1](/packages/alekseykorzun-memcached-wrapper-php)[rapidwebltd/rw-file-cache

RW File Cache is a PHP File-based Caching Library. Its syntax is designed to closely resemble the PHP memcache extension.

15191.3k7](/packages/rapidwebltd-rw-file-cache)[antennaio/laravel-clyde

Image uploads and manipulation for Laravel, a wrapper around Glide

292.6k](/packages/antennaio-laravel-clyde)[swiggles/memcache

Memcache driver for Laravel 5

1449.9k1](/packages/swiggles-memcache)

PHPackages © 2026

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