laravel-model-cache maintained by daika7ana
Description
Laravel package for caching Eloquent model queries
Authors
daika7ana - Yordan
Last update
2026/10/13 18:41
(dev-master)
License
Downloads
5
Tags
redis - orm - performance - php - cache - caching - memcached - model - laravel - eloquent - laravel-package - model-cache - laravel-eloquent - database-caching - query-cacher
Laravel Model Cache
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.