daika7ana / laravel-model-cache
Laravel package for caching Eloquent model queries
v1.0.1
2026-10-13 16:41 UTC
Requires
- php: ^8.2
- ext-json: *
- illuminate/cache: ^11.0|^12.0|^13.0
- illuminate/database: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
Requires (Dev)
- laravel/pint: ^1.27
- orchestra/testbench: ^9.0|^10.0|^11.0
- phpunit/phpunit: ^11.0|^12.0|^13.0
Suggests
- ext-memcached: Required for tag-based cache invalidation with Memcached
- ext-redis: Required for tag-based cache invalidation with Redis
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-10-13 16:42:09 UTC
README
Cache Eloquent queries with minimal code changes and automatic invalidation.
This repository is a fork of the original project by Yordan: https://github.com/ymigval/laravel-model-cache
Features
- Automatic caching of
get(),first(),count(), other aggregates, andpaginate()via a drop-in builder. - Tag-based invalidation on create/update/delete/restore and all mass operations.
- Transaction-aware — flushes are deferred until commit, never on rollback.
- Fail-open — cache errors fall through to the database instead of crashing.
- Stampede prevention — optional cache locking for concurrent cache misses.
- Per-model configuration — cache duration, key prefix, and lock duration per model.
Requirements
- PHP
^8.2 - Laravel
11.xthrough13.x - Redis or Memcached for tag-based invalidation (recommended)
Quick Start
1) Install
composer require daika7ana/laravel-model-cache
2) Add the trait to a model
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Daika7ana\LaravelModelCache\HasCachedQueries; class Post extends Model { use HasCachedQueries; protected $cacheMinutes = 120; // optional: TTL in minutes (default: config) protected $cachePrefix = 'posts_'; // optional: key prefix (default: config) protected $cacheLockSeconds = 15; // optional: stampede lock duration (default: config) }
Tip: Use
HasCacheableModelinstead to also invalidate the cache onbelongsToManyattach/detach/sync.
3) Query as usual
$posts = Post::where('published', true)->get(); // cached automatically $featured = Post::where('featured', true)->remember(30)->get(); // per-query TTL $fresh = Post::where('featured', true)->withoutCache()->get(); // bypass cache
Explicit variants (getFromCache(), firstFromCache(), paginateFromCache()) are also available.
Clearing the cache
php artisan mcache:flush # all cached models php artisan mcache:flush "App\\Models\\Post" # one model
Documentation
How-to guides — start at docs/README.md:
- How to install and configure
- How to use in models and queries
- Examples
- API reference
- How to clear cache
- How to troubleshoot common issues
Contributing
See CONTRIBUTING.md.
License
MIT. See LICENSE.md.