应使用 composer require renatomarinho/laravel-model-cache 命令安装,而非 laravel-model-cache;需手动在模型中引入 Cacheable trait、注册服务提供者,并注意其仅缓存 find/first 等单记录查询,列表查询需自行用 Cache::remember 处理。

composer require 装不上 laravel-model-cache 怎么办
这个包的官方名称其实是 renatomarinho/laravel-model-cache,不是 laravel-model-cache。直接搜错名字、敲错仓库名是装不上的最常见原因。
- 用错命令:别写
composer require laravel-model-cache(会报Could not find package laravel-model-cache) - 正确命令是:
composer require renatomarinho/laravel-model-cache - Laravel 9+ 默认启用了 Composer v2 的插件安全策略,如果包没在 Packagist 官方索引里(比如 fork 的非主分支),会拒绝安装——确认你用的是原作者主仓库
- 如果项目启用了
minimum-stability: stable,而该包最新版只有dev-main,得临时加--with-all-dependencies或改composer.json的 stability 设置
装完之后模型不缓存?检查 service provider 和 trait 引入
包本身不会自动给所有模型加缓存,必须手动在每个想缓存的模型里加 Cacheable trait,并注册服务提供者。
- 确保
RenatoMarinho\LaravelModelCache\CacheServiceProvider::class已加到config/app.php的providers数组里(Laravel 5.5+ 可能自动发现,但建议显式确认) - 模型里必须用
use Cacheable;,不能只写use RenatoMarinho\LaravelModelCache\Traits\Cacheable;(后者路径不对,会报Trait 'Cacheable' not found) -
Cacheabletrait 依赖cache驱动正常工作,如果php artisan cache:clear报错,先查CACHE_DRIVER是否设为redis或memcached——文件驱动对高频读场景基本无效
find() 缓存了,但 where() / paginate() 不走缓存?这是设计如此
这个包默认只对 find()、findOrFail()、first()(带主键条件时)等“确定性单记录查询”做缓存。像 where('status', 1)->get() 或 paginate() 这类动态查询,它压根不拦截,也不会缓存结果。
- 它缓存的是“主键 → 模型实例”,不是 SQL → 结果集,所以没有通用查询缓存能力
- 如果真需要缓存列表,得自己用
Cache::remember()包一层,例如:Cache::remember('users-active', 3600, fn() => User::where('active', 1)->get()) - 注意:
Cacheable的remember()方法只适用于主键查找,别误以为能替代手动缓存逻辑
缓存没失效?重点看 touch()、save() 和关系更新场景
模型更新时,包会自动清对应主键缓存,但有几个关键漏点:
- 批量更新(
User::where(...)->update([...]))不会触发缓存清理,得手动Cache::forget('user:123')或用Cache::flush()(慎用) - 关系模型变更(比如给用户新增一个
Post)不会自动清父模型缓存,除非你在Post的creating事件里显式 touch 用户 -
touch()方法本身只更新updated_at,但不会触发缓存刷新——得配合$model->saveQuietly()+ 自定义清除逻辑,或改用监听saved事件
缓存键命名规则是 "{$table}:{$id}",如果你改过模型的 $table 或 $primaryKey,但没重写 getCacheKey(),就可能删错键或读不到缓存。这种细节一漏,问题就藏得深。











