Download the PHP package mikebronner/laravel-model-caching without Composer

On this page you can find all versions of the php package mikebronner/laravel-model-caching. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-model-caching

πŸš€ Model Caching for Laravel

Latest Stable Version Laravel Laravel Package PHP Version Packagist codecov Tests GitHub Stars GitHub license

Model Caching for Laravel masthead image

πŸ—‚οΈ Table of Contents

πŸ“– Summary

Automatic, self-invalidating Eloquent model and relationship caching. Add a trait to your models and all query results are cached automatically β€” no manual cache keys, no forgetting to invalidate. When a model is created, updated, or deleted the relevant cache entries are flushed for you.

⚑ Typical performance improvements range from 100–900% reduction in database queries on read-heavy pages. πŸ§ͺ Backed by 335+ integration tests across PHP 8.2–8.5 and Laravel 11–13.

Use this package when your application makes many repeated Eloquent queries and you want a drop-in caching layer that stays in sync with your data without any manual bookkeeping.

πŸ”„ Before & After

❌ Without this package β€” manual cache keys, manual invalidation:

βœ… With this package β€” add the trait, query normally:

βœ… What Gets Cached

🚫 What Does Not Get Cached

πŸ’Ύ Cache Drivers

Driver Supported
Redis βœ… (recommended)
Memcached βœ…
APC βœ…
DynamoDB βœ…
Array ❌
File ❌
Database ❌

πŸ“‹ Requirements

πŸ“¦ Installation

✨ The service provider is auto-discovered. No additional setup is required.

πŸš€ Getting Started

Add the Cachable trait to your models. The recommended approach is a base model that all other models extend:

Alternatively, extend the included CachedModel directly:

πŸŽ‰ That's it β€” all Eloquent queries and eager-loaded relationships on these models are now cached and automatically invalidated.

⚠️ Note: You can cache the User model β€” the Cachable trait does not conflict with Laravel's authentication. Just avoid using cache cool-down periods on it, and ensure user updates always go through Eloquent (not raw DB::table() queries) so cache invalidation fires correctly.

🌍 Real-World Example

Consider a blog with posts, comments, and tags:

When a new comment is created, the cache for Post and Comment queries is automatically invalidated β€” no manual Cache::forget() calls needed. 🧹

βš™οΈ Configuration

Publish the config file:

This creates config/laravel-model-caching.php:

πŸ”§ Environment Variables

Variable Default Description
MODEL_CACHE_ENABLED true βœ… Enable or disable caching globally.
MODEL_CACHE_STORE null πŸ’Ύ Cache store name from config/cache.php. Uses the default store when not set.
MODEL_CACHE_USE_DATABASE_KEYING true πŸ”‘ Include database connection and name in cache keys. Important for multi-tenant or multi-database apps.
MODEL_CACHE_FALLBACK_TO_DB false πŸ›‘οΈ When true, falls back to direct database queries if the cache backend is unavailable (e.g. Redis is down) instead of throwing an exception.

πŸ“ Note: The cache-prefix option is set directly in the config file (not via an environment variable). For dynamic prefixes (e.g. multi-tenant), use the per-model $cachePrefix property shown below.

πŸ’Ύ Custom Cache Store

To use a dedicated cache store for model caching, define one in config/cache.php and reference it:

☁️ DynamoDB Cache Store

DynamoDB is supported when your selected Laravel cache store uses the dynamodb driver:

Define the store in config/cache.php using the same fields Laravel documents for the DynamoDB cache driver:

If your application does not already require it, install the AWS SDK:

Enable DynamoDB TTL on the table's expires_at attribute as described in the Laravel cache docs.

How invalidation works on DynamoDB

Model invalidation on DynamoDB uses logical namespace versioning instead of native cache tags:

This package does not issue table scans or destructive flushes on DynamoDB.

TTL guidance

Laravel's DynamoDB cache store writes forever() entries with a long-lived expiration instead of a truly unbounded item. In current Laravel releases that window is several years, which means stale DynamoDB rows are bounded but can linger for a long time after invalidation.

Practical guidance:

Operational notes

Troubleshooting

When to use DynamoDB vs Redis

🏷️ Cache Key Prefix

For multi-tenant applications you can isolate cache entries per tenant. Set the prefix globally in config:

Or per-model via a property:

πŸ”Œ Multiple Database Connections

When use-database-keying is enabled (the default), cache keys automatically include the database connection and name. This keeps cache entries separate across connections without any extra configuration.

🚫 Disabling Cache

There are three ways to bypass caching:

1. Per-query (only affects this query chain, not subsequent queries):

2. Globally via environment:

3. For a block of code:

πŸ’‘ Tip: Use option 1 in seeders to avoid pulling stale cached data during reseeds.

❄️ Cache Cool-Down Period

In high-traffic scenarios (e.g. frequent comment submissions) you may want to prevent every write from immediately flushing the cache. Cool-down requires two steps:

Declare the default duration on the model (this alone does nothing β€” it just sets the value):

Activate the cool-down by calling withCacheCooldownSeconds() in your query. This writes the cool-down window into the cache store:

Once activated, writes during the cool-down window will not flush the cache. After the window expires, the next write triggers a flush and re-warms the cache. πŸ”„

πŸ›‘οΈ Graceful Fallback

When enabled, if the cache backend (e.g. Redis) is unavailable the package logs a warning and falls back to querying the database directly β€” your application continues to function without caching rather than throwing an exception.

🧹 Cache Invalidation

Cache is automatically flushed when:

Trigger Behavior
Model created Flush model cache
Model updated/saved Flush model cache
Model deleted Flush only if rows were actually deleted
Model force-deleted Flush only if rows were actually deleted
Pivot attach / detach / sync / updateExistingPivot Flush relationship cache
increment / decrement Flush model cache
insert / update (builder) Flush model cache
truncate Flush model cache

Cache tags are generated for the primary model, each eager-loaded relationship, joined tables, and morph-to target types, so only the relevant entries are invalidated. 🎯

πŸ”— BelongsToMany with Custom Pivot Models

Cache invalidation works for BelongsToMany relationships using custom pivot models (->using(CustomPivot::class)) as long as either the parent or the related model uses the Cachable trait.

🧹 Manual Cache Flushing

Artisan command β€” single model:

Artisan command β€” all models:

ℹ️ Scope of the full clear (no --model) β€” how much is removed depends on the cache driver:

  • Redis (with a cache-store prefix) β€” only the model-cache keys are scanned and deleted; other keys on the same connection are left intact. This honors both the connection-level client prefix (database.redis.options.prefix) and the cache-store prefix, and works on the phpredis and Predis clients, single-node or cluster (CROSSSLOT-safe).
  • DynamoDB β€” rotates a package-wide namespace key; no destructive table scan (see the DynamoDB section).
  • Memcached, file, database, or un-prefixed Redis β€” these cannot scope a clear by prefix, so the entire cache store is flushed. Give the model cache a dedicated store (see the Custom Cache Store section) so a full clear never touches unrelated data.

πŸ”§ Programmatic via Facade:

⏰ Cache Expiration (TTL)

Cached queries are stored indefinitely (rememberForever) and rely on automatic invalidation (see above) to stay fresh. There is no per-query TTL option. If you need time-based expiry, use the cool-down period feature or flush the cache on a schedule via the Artisan command.

πŸ§ͺ Testing

In your test suite you can either disable model caching entirely or use the array cache driver:

🚫 Disable caching in tests:

βœ… Use the array driver (useful for testing cache behavior itself):

πŸ‘· Queue Workers

The package has no special queue or Horizon integration. Cached queries inside queued jobs work the same as in HTTP requests. Cache invalidation triggered in a web request is immediately visible to queue workers (assuming a shared cache store like Redis). No additional configuration is needed.

πŸ” Static Analysis (Larastan / PHPStan)

The package is compatible with Larastan at level 5 and above. Because the Cachable trait wraps Eloquent's builder, PHPStan may report "undefined method" errors for methods like cache() or flushCache() on your models. To resolve these, add a @mixin annotation to your cached model:

If you use a custom Eloquent builder that gets wrapped by CachedBuilder, PHPStan cannot infer the custom methods from the CachedBuilder return type. Add a @return override annotation on your model's newEloquentBuilder() method, or add @mixin YourCustomBuilder to the model class.

The package ships with a phpstan-baseline.neon that suppresses internal analysis errors in the package's own test fixtures. These do not affect consumer projects.

🀝 Contributing

Contributions are welcome! πŸŽ‰ Please review the Contribution Guidelines and observe the Code of Conduct before submitting a pull request.

⬆️ Upgrading

For breaking changes and upgrade instructions between versions, see the Releases page on GitHub.

πŸ” Security

Please review the Security Policy for information on supported versions and how to report vulnerabilities.

πŸ“š Further Reading

The test suite serves as living documentation β€” browse it for detailed examples of every supported query type, relationship pattern, and edge case. πŸ“–


Built with ❀️ for the Laravel community using lots of β˜•οΈ by Mike Bronner.

This is an MIT-licensed open-source project. Its continued development is made possible by the community. If you find it useful, please consider πŸ’– becoming a sponsor and ⭐ing it on GitHub.

πŸ™ Thank you to all contributors who have helped make this package better!


All versions of laravel-model-caching with dependencies

PHP Build Version
Package Version
Requires php Version >=8.2
mikebronner/laravel-pivot-events Version *
illuminate/cache Version ^11.0|^12.0|^13.0
illuminate/config Version ^11.0|^12.0|^13.0
illuminate/console Version ^11.0|^12.0|^13.0
illuminate/container Version ^11.0|^12.0|^13.0
illuminate/database Version ^11.0|^12.0|^13.0
illuminate/http Version ^11.0|^12.0|^13.0
illuminate/support Version ^11.0|^12.0|^13.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package mikebronner/laravel-model-caching contains the following files

Loading the files please wait ...