Download the PHP package ymigval/laravel-model-cache without Composer

On this page you can find all versions of the php package ymigval/laravel-model-cache. 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-cache

Laravel Model Cache

A simple and efficient caching solution for Laravel Eloquent models.

Latest Version on Packagist Total Downloads

Introduction

Laravel Model Cache provides a powerful way to cache your Eloquent query results. It transparently integrates with Laravel's query builder system to automatically cache all query results, with zero changes to your existing query syntax. The package intelligently handles cache invalidation when models are created, updated, deleted, or restored.

Features

Requirements

Installation

Install the package via Composer:

Publish the Configuration File (optional)

To customize the package configuration, publish the configuration file:

This creates with the following customizable options: config/model-cache.php

Service Provider Registration

The package comes with Laravel package auto-discovery for Laravel 5.5+. For older versions, register the service provider in : config/app.php

Cache Driver Configuration

Supported Cache Drivers

This package uses Laravel's tagging system for cache, so you must use a cache driver that supports tags:

  1. Redis (Recommended)

    • Offers excellent performance and tag support
    • Configure in .env:
  2. Memcached

    • Another good option with tag support
    • Configure in .env:
  3. Database
    • Supports tags but slower than Redis/Memcached
    • Requires cache table creation:
  1. File and Array drivers do not support tags, but the package includes fallback mechanisms that make them compatible:
    • These drivers will work for basic caching functionality
    • When using these drivers, cache invalidation will clear the entire cache rather than just specific model entries
    • While not as efficient as tag-supporting drivers, they can be used in development or when other drivers are not available
    • Configure in .env:

Optional Configuration in Config File

The file allows you to adjust: config/model-cache.php

Cache Store Selection

You can specify which cache store to use specifically for model caching in the config file:

This allows you to use a different cache store for models than your application's default cache store.

Implementation in Models

Add the trait to any Eloquent model you want to cache:

How Caching Works

This package takes a unique approach to model caching by replacing the standard Eloquent query builder with a cache-aware version. The HasCachedQueries trait overrides the newEloquentBuilder() method to return a CacheableBuilder instance instead of the standard builder.

Technical Details:

  1. Query Builder Replacement: When you add the trait to a model, all queries for that model will use the custom builder
  2. Automatic Caching: All standard Eloquent query methods (get(), first(), etc.) automatically check cache first
  3. Cache Key Generation: Unique cache keys are created based on the SQL query, bindings, and model
  4. Event-Based Invalidation: Cache is automatically cleared when models are created, updated, deleted, or restored

Cache Usage Options

The package offers two complementary approaches to caching:

1. Implicit Caching (Standard Eloquent Methods)

When your model uses the HasCachedQueries trait, standard Eloquent methods automatically use the cache:

2. Explicit Caching Methods

For more explicit control and code readability, use the dedicated caching methods:

Both approaches produce the same result - they check the cache first and only hit the database if needed.

Choosing Between Implicit and Explicit Caching

Both approaches have advantages depending on your use case:

Approach When to Use Benefits
Implicit (get()) For seamless integration into existing code - No code changes needed
- Transparent performance boost
- Works with existing code
Explicit (getFromCache()) When you want caching to be obvious - Self-documenting code
- Clearer for team members
- Highlights performance considerations

Performance Comparison

There is no performance difference between the two approaches - both implementations use the same underlying caching mechanism. The choice is purely about code readability and developer preference.

Advanced Caching Strategies

Using Query Scopes with Caching

Combine Laravel scopes with cache settings for reusable cached queries:

Conditional Caching

Dynamically decide whether to cache based on conditions:

Selective Caching with Relations

Cache only specific relations:

Manually Clearing Cache Using Console Commands

Laravel Model Cache includes built-in Artisan commands to easily clear the cache for your models from the command line. This feature is especially useful when you need to manually invalidate cache during deployments or when troubleshooting.

Available Cache Clearing Commands

The package registers the following Artisan command:

The {model?} parameter is optional. When provided, it should be the fully qualified class name of the model you want to clear the cache for.

Command Usage Examples

Clear Cache for a Specific Model

To clear the cache for a specific model, provide the fully qualified class name:

The command will:

  1. Instantiate the model class
  2. Call the flushModelCache() method or clear the cache manually
  3. Display a confirmation message when complete

Clear Cache for All Models

To clear the cache for all models at once, run the command without any arguments:

This will clear all cache entries tagged with 'model_cache', effectively clearing the cache for all models that use the package.

How the Command Works

  1. Tag-Based Clearing

    • The command uses cache tags to efficiently clear only relevant cache entries
    • Tags are structured as ['model_cache', ModelClassName, TableName]
    • This is efficient as it only removes cache related to the specified model
  2. Fallback for Non-Tag-Supporting Drivers
    • For cache drivers that don't support tags (File, Database), the command falls back to clearing all cache
    • The command will display a warning and ask for confirmation before proceeding with a full cache clear
    • This is necessary because without tag support, it's not possible to selectively clear only model-related cache

Programmatic Cache Clearing

You can also clear the cache programmatically in your application code:

When to Use Cache Clearing Commands

Consider manually clearing cache in these situations:

  1. Deployments: After deploying new code that might make cached data obsolete
  2. Data Imports: After bulk importing data that bypasses model events
  3. Schema Changes: After changing database schema that affects model structures
  4. Debugging: When troubleshooting issues that might be related to stale cache

Performance Considerations

Using ModelRelationships Trait

The ModelRelationships trait provides enhanced support for cache invalidation when working with Eloquent relationships. It automatically flushes the cache when relationship operations (like attaching, detaching, or syncing pivot records) are performed.

Implementation in Models

Add both traits to your model:

Using Helper Methods for Relationships

The trait provides convenient methods to manipulate relationships while ensuring the cache is properly invalidated:

Automatic Cache Invalidation

The trait also registers event listeners that automatically flush the cache when Laravel's relationship methods are used:

This ensures that your cached queries always reflect the current state of your model relationships.

Troubleshooting

Cache Not Being Used

If your queries are not being cached:

  1. Verify that your model correctly uses the HasCachedQueries trait
  2. Check that you're using a compatible cache driver (Redis, Memcached, Database)
  3. Make sure that model-cache.enabled is set to true in your configuration
  4. Temporarily add logging to verify if cache hits or misses are occurring:

Cache Not Being Invalidated

If old data persists in the cache after updates:

  1. Make sure your model is correctly firing create/update/delete events
  2. Check if you're using query builder methods that bypass model events (DB::table()->update())
  3. Try manually clearing the cache to test: YourModel::flushModelCache()
  4. Verify that your cache driver correctly supports tags if you're using them

Frequently Asked Questions

Q: Why use this package instead of Laravel's built-in caching?

A: This package provides automatic cache invalidation, tag-based cache management, and seamless integration with Eloquent with minimal code changes.

Q: Does this work with soft deleted models?

A: Yes, the package respects Laravel's soft delete functionality and will cache accordingly.

Q: What's the difference between get() and getFromCache()?

A: Functionally they are identical when using this package - both check cache first. The difference is syntax preference and code readability.

Q: Can I still use regular database queries when needed?

A: Yes, you can bypass the cache using:

Q: Does this work with relationships?

A: Yes, caching works with eager-loaded relationships and regular relationship queries. The package correctly generates unique cache keys for queries with different eager-loaded relationships, ensuring that Model::get() and Model::with(['relation'])->get() use different cache entries.

Q: How can I troubleshoot cache issues?

A: You can enable debug mode in your configuration file to see detailed logs about cache keys being generated:

Migrating from Other Caching Solutions

From Manual Laravel Cache

If you're currently using Laravel's Cache facade manually:

From Other Cache Packages

If you're using another caching package:

  1. Replace the other package's trait with HasCachedQueries
  2. Remove manual cache key generation code
  3. Replace custom cache retrieval methods with standard Eloquent methods or the explicit getFromCache() methods
  4. Remove manual cache invalidation code (this package handles it automatically)

All versions of laravel-model-cache with dependencies

PHP Build Version
Package Version
Requires php Version ^7.4|^8.0|^8.1|^8.2|^8.3
illuminate/support Version ^8.0|^9.0|^10.0|^11.0|^12.0
illuminate/database Version ^8.0|^9.0|^10.0|^11.0|^12.0
illuminate/cache Version ^8.0|^9.0|^10.0|^11.0|^12.0
ext-json Version *
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 ymigval/laravel-model-cache contains the following files

Loading the files please wait ....