codewithdennis/laravel-model-cache
Composer 安装命令:
composer require 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.
README 文档
README
Currently in a testing phase and no where near a release
Add the trait to a model and get TTL-based query caching. Optionally use pre-warming to cache heavy queries indefinitely.
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
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)
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)
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
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 is invalidated automatically on model created, updated, deleted, and restored (soft deletes) events.
Requirements
- PHP 8.4+
- Laravel 12.x
Uses your Laravel cache (see config/cache.php). Models without the trait are not cached.
License
MIT. See LICENSE.md for details.
codewithdennis/laravel-model-cache 适用场景与选型建议
codewithdennis/laravel-model-cache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 14 次下载、GitHub Stars 达 7, 最近一次更新时间为 2026 年 02 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「performance」 「cache」 「laravel」 「eloquent」 「ttl」 「Query Cache」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 codewithdennis/laravel-model-cache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 codewithdennis/laravel-model-cache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 codewithdennis/laravel-model-cache 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
g4 application profiler package
repository php library
CSS/Javascript Minificator, Compressor and Concatenator for TYPO3 - highly configurable frontend asset optimization for CSS/JS merging, minification and compression with optional body parsing, async/defer loading, inline output, data-ignore exclusions, SRI integrity validation/calculation, external
WordPress mu-plugin to remove jQuery Migrate from the list of jQuery dependencies and to allow jQuery to enqueue before </body> instead of in the <head>.
Create link to static resources with cache-breaking segment based on md5 of the file
Laravel 5 - Repositories to the database layer
统计信息
- 总下载量: 14
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 7
- 点击次数: 29
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-02-01