Search by

daika7ana / laravel-model-cache

daika7ana

Laravel package for caching Eloquent model queries

Package info

github.com/daika7ana/laravel-model-cache

pkg:composer/daika7ana/laravel-model-cache

Statistics

Installs: 5

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.1 2026-10-13 16:41 UTC

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.

Latest Version on Packagist Total Downloads License

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, and paginate() 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.x through 13.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 HasCacheableModel instead to also invalidate the cache on belongsToMany attach/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:

Contributing

See CONTRIBUTING.md.

License

MIT. See LICENSE.md.