Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Model Cache Laravel Package

ymigval/laravel-model-cache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal steps:

  1. Install via Composer:
    composer require ymigval/laravel-model-cache
    
  2. Add the HasCachedQueries trait to your Eloquent model:
    use YMigVal\LaravelModelCache\HasCachedQueries;
    
    class Post extends Model
    {
        use HasCachedQueries;
    }
    
  3. Publish config (optional):
    php artisan vendor:publish --provider="YMigVal\LaravelModelCache\ModelCacheServiceProvider" --tag="config"
    

First use case: Cache a simple query in a controller:

// Automatically cached for 60 minutes (config default)
$posts = Post::where('published', true)->get();

Implementation Patterns

1. Basic Query Caching

// Implicit caching (default behavior)
$posts = Post::where('status', 'active')->get();

// Explicit caching (more readable)
$posts = Post::where('status', 'active')->getFromCache();

2. Model-Specific Configuration

class Post extends Model
{
    use HasCachedQueries;

    // Override default cache duration (2 hours)
    protected $cacheMinutes = 120;

    // Custom cache prefix
    protected $cachePrefix = 'posts_';
}

3. Dynamic Cache Duration

$cacheMinutes = $user->isAdmin() ? 5 : 60;
$posts = Post::where('status', 'active')->remember($cacheMinutes)->get();

4. Conditional Caching

$posts = Post::when($forceFresh, function($query) {
    return $query->withoutCache();
})->get();

5. Relationship Caching

// Cache posts with fresh comments
$posts = Post::with(['comments' => function($query) {
    $query->withoutCache();
}])->remember(30)->get();

6. Cache Invalidation Workflow

// In controller after update
$post->save(); // Automatically invalidates cache
// OR manually
Post::flushModelCache();

7. Command-Line Cache Management

# Clear cache for specific model
php artisan mcache:flush "App\Models\Post"

# Clear all model caches
php artisan mcache:flush

8. Scope Integration

// In model
public function scopePopular($query)
{
    return $query->where('views', '>', 1000)
                ->remember(60); // Cache popular posts for 1 hour
}

// In controller
$posts = Post::popular()->get(); // Automatically cached

Gotchas and Tips

Pitfalls:

  1. Tag Support Requirement: Non-tag drivers (file/array) will clear entire cache on invalidation
  2. Cache Key Collisions: Complex queries with identical SQL but different bindings may share cache
  3. Event Timing: Model events must fire for automatic invalidation to work
  4. Relation Caching: Nested relations may not cache as expected without explicit configuration
  5. Debugging: Cache keys can be long and complex; use config('model-cache.cache_key_prefix') to identify them

Debugging Tips:

  1. Check cache keys with:
    $key = Post::where('id', 1)->get()->getCacheKey();
    
  2. Verify cache tags exist:
    Cache::tags(['model_cache'])->get('model_cache:App\Models\Post:select * from posts where id = 1');
    
  3. Use withoutCache() to bypass cache for testing:
    Post::withoutCache()->get();
    

Configuration Quirks:

  1. Set enabled: false in config to disable globally
  2. Use cache_store to specify a dedicated cache driver for models
  3. Adjust cache_duration per-model or globally

Extension Points:

  1. Custom Cache Keys: Override getCacheKey() in your model
  2. Custom Invalidation: Extend flushCache() for model-specific logic
  3. Cache Events: Listen to modelCache:cleared events for side effects
  4. Query Modifiers: Add custom query conditions before caching with getCacheQuery()

Performance Optimization:

  1. Use shorter cache durations for frequently updated models
  2. Implement cache warming for critical paths
  3. Consider separate cache stores for read-heavy vs write-heavy models
  4. Monitor cache hit ratios with:
    Cache::stats(); // For Redis/Memcached
    

Common Pitfalls and Solutions:

Issue Solution
Cache not updating after model save Ensure model events are firing; check observables array in model
Entire cache cleared unexpectedly Verify cache driver supports tags; check for manual Cache::flush() calls
Complex queries not caching Simplify query or use explicit cache keys
Memory issues with large caches Implement pagination or shorter cache durations
Race conditions with cache invalidation Use Cache::lock() for critical operations
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky