PHPackages                             codewithdennis/laravel-model-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. [Database &amp; ORM](/categories/database)
4. /
5. codewithdennis/laravel-model-cache

ActiveLibrary[Database &amp; ORM](/categories/database)

codewithdennis/laravel-model-cache
==================================

Pre-warm and cache Eloquent query results. Run heavy queries once with warmup (forever cache) or use TTL-based caching on any model.

v1.0.0-beta.1(3mo ago)714[1 PRs](https://github.com/CodeWithDennis/laravel-model-cache/pulls)MITPHPPHP ^8.4.0CI passing

Since Feb 1Pushed 2mo agoCompare

[ Source](https://github.com/CodeWithDennis/laravel-model-cache)[ Packagist](https://packagist.org/packages/codewithdennis/laravel-model-cache)[ GitHub Sponsors](https://github.com/CodeWithDennis)[ RSS](/packages/codewithdennis-laravel-model-cache/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (3)Used By (0)

Cache Pre-Warming
=================

[](#cache-pre-warming)

> **Currently in a testing phase and no where near a release**

[![Tests](https://github.com/CodeWithDennis/laravel-model-cache/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/CodeWithDennis/laravel-model-cache/actions/workflows/tests.yml)[![License](https://camo.githubusercontent.com/27694548f1a57219839cbe0acfa18387e87075691dc33e34ba30ef0446a2a651/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f436f64655769746844656e6e69732f6c61726176656c2d6d6f64656c2d6361636865)](https://github.com/CodeWithDennis/laravel-model-cache/blob/master/LICENSE.md)[![PHP Version](https://camo.githubusercontent.com/25b539b9c19d8dcd0ac4dea0280d0023ad30e57472ebefc0d135c97fb171255f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f636f64657769746864656e6e69732f6c61726176656c2d6d6f64656c2d6361636865)](https://packagist.org/packages/codewithdennis/laravel-model-cache)[![Laravel](https://camo.githubusercontent.com/5b99ec644e12357132ddb95970822afd67efedef92fcccb6270926adebd8b101/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31322e782d726564)](https://laravel.com)

Add the trait to a model and get TTL-based query caching. Optionally use pre-warming to cache heavy queries indefinitely.

---

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

[](#installation)

```
composer require codewithdennis/laravel-model-cache
```

**Cache driver:** Use a driver that supports tags (`array`, `redis`, or `memcached`). The `file` and `database` drivers do not support tagging; cache invalidation on model events will not work with them.

Add the trait to any model:

```
use CodeWithDennis\LaravelModelCache\Traits\HasCache;

class User extends Model
{
    use HasCache;
}
```

---

Part 1: Normal Caching
----------------------

[](#part-1-normal-caching)

With the trait added, every query is cached after it runs. The first run hits the database and stores the result; later runs with the same query read from cache until it expires (default 10 minutes).

**Use it for:** data that changes now and then.

**Example**

```
$users = User::query()
    ->where('active', true)
    ->orderBy('name')
    ->get();
```

The first call hits the database. The next calls with the same query use the cache until the TTL expires, then the next request refreshes it from the database.

**Configuration** — Change how long the cache lasts:

```
public function cacheTtl(): int
{
    return 3600; // 1 hour
}
```

or

```
protected int $cacheTtl = 300; // 5 minutes
```

---

Part 2: Pre-Warming (additional feature)
----------------------------------------

[](#part-2-pre-warming-additional-feature)

Pre-warming caches a query indefinitely by running it ahead of time (e.g. in a scheduled command). The first visitor and everyone after get the result from cache—no slow first request.

**Why use it?** — Without pre-warming, the first user who hits a heavy query pays the full cost: the database runs it, and they wait. Everyone else benefits from the cache. Pre-warming runs that query once (e.g. in a scheduled job or right after deploy) and fills the cache. When the first user arrives, the result is already there—no cold start.

**Use it for:** data that rarely changes—dashboard stats, totals, reference data.

**Example**

Call `warmup()` before the query:

```
$stats = User::query()
    ->where('active', true)
    ->where('created_at', '>=', now()->startOfMonth())
    ->orderBy('created_at')
    ->warmup()
    ->get();
```

**Run it in a command** — Put the query in a Laravel command and schedule it (e.g. hourly or after deploy). When the command runs, it fills the cache. The next user request gets the result from cache.

```
// app/Console/Commands/WarmCache.php
class WarmCache extends Command
{
    protected $signature = 'cache:warm';

    public function handle(): int
    {
        User::query()
            ->where('active', true)
            ->where('created_at', '>=', now()->startOfMonth())
            ->orderBy('created_at')
            ->warmup()
            ->get();

        return self::SUCCESS;
    }
}
```

```
// routes/console.php
Schedule::command('cache:warm')->hourly();
```

**What does warmup() do?** — It stores the result with no expiry instead of using the model’s TTL. Same caching behaviour, no expiry.

---

How it works (diagram)
----------------------

[](#how-it-works-diagram)

 ```
flowchart LR
  A1[Command runs] --> B1["Run query (with warmup)"]
  B1 --> C1[Cache with No TTL]
  C1 --> D[Request]
  A2[First request] --> B2[Run query]
  B2 --> C2[Cache with TTL]
  C2 --> D
  D --> E[Cache hit]
  E -->|TTL only| F["After TTL → DB again"]
```

      Loading Left path: pre-warming (cache forever). Right path: normal caching (cache for a set time; when it expires, the next request hits the database again).

---

Supported methods
-----------------

[](#supported-methods)

Both normal caching and pre-warming support:
`get`, `first`, `find`, `findMany`, `pluck`, `value`, `sole`, `count`, `exists`, `doesntExist`, `sum`, `avg`, `average`, `min`, `max`, `paginate`, `simplePaginate`.

---

Cache invalidation
------------------

[](#cache-invalidation)

Cache is invalidated automatically on model **created**, **updated**, **deleted**, and **restored** (soft deletes) events.

---

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

[](#requirements)

- PHP 8.4+
- Laravel 12.x

Uses your Laravel cache (see `config/cache.php`). Models without the trait are not cached.

---

License
-------

[](#license)

MIT. See [LICENSE.md](LICENSE.md) for details.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance82

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

106d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6d47a56dfab94e67a7354a146f96a0285c09f6b9d649c558832c6a9b94354b8c?d=identicon)[CodeWithDennis](/maintainers/CodeWithDennis)

---

Top Contributors

[![CodeWithDennis](https://avatars.githubusercontent.com/u/23448484?v=4)](https://github.com/CodeWithDennis "CodeWithDennis (67 commits)")

---

Tags

cachecachingeloquentlaravellaravel12performancepre-warmingquery-cachettlwarmuplaravelperformanceeloquentcachewarmupmodel-cacheQuery Cachettlpre-warming

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/codewithdennis-laravel-model-cache/health.svg)

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

###  Alternatives

[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[ymigval/laravel-model-cache

Laravel package for caching Eloquent model queries

7642.2k3](/packages/ymigval-laravel-model-cache)[kirkbushell/eloquence

A set of extensions adding additional functionality and consistency to Laravel's awesome Eloquent library.

573970.0k1](/packages/kirkbushell-eloquence)[mostafaznv/laracache

LaraCache is a customizable cache trait to cache queries on model's events

27246.8k1](/packages/mostafaznv-laracache)[adobrovolsky97/laravel-repository-service-pattern

Laravel 5|6|7|8|9|10 - Repository - Service Pattern

275.4k](/packages/adobrovolsky97-laravel-repository-service-pattern)[stayallive/laravel-eloquent-observable

Register Eloquent model event listeners just-in-time directly from the model.

2928.9k7](/packages/stayallive-laravel-eloquent-observable)

PHPackages © 2026

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