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 Cacheable Model Laravel Package

elipzis/laravel-cacheable-model

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation** (Laravel 10+ and PHP 8.5+):
   ```bash
   composer require elipzis/laravel-cacheable-model
   php artisan vendor:publish --provider="ElipZis\Cacheable\CacheableServiceProvider"

Publish the config file to customize defaults (e.g., cache driver, TTL, or Laravel 13 compatibility settings).

  1. Enable Caching: Add the Cacheable trait to your Eloquent model:

    use ElipZis\Cacheable\Models\Traits\Cacheable;
    
    class Post extends Model
    {
        use Cacheable;
    }
    
  2. First Use Case: Immediately cache queries like this:

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

    The package now handles edge cases like whereNull() safely (fixed in v0.6.0).


Where to Look First

  • Config File: config/cacheable.php – Adjust TTL, cache driver, and query hashing strategy. Check for Laravel 13-specific optimizations.
  • Model Trait: ElipZis\Cacheable\Models\Traits\Cacheable – Understand how caching is triggered, including new PHP 8.5 type safety.
  • Cache Keys: Logged in storage/logs/laravel.log (debug level) to verify keys. Enable debug mode with:
    Cacheable::setDebug(true);
    

Implementation Patterns

Core Workflows

  1. Automatic Caching (with edge-case fixes):

    // All `get()`, `first()`, `find()`, etc., are cached automatically.
    $user = User::find(1); // Cached under `user:1`
    $posts = Post::whereNull('deleted_at')->get(); // Now handles `whereNull` safely
    
  2. Customizing Cache Keys: Override the getCacheKey() method in your model:

    public function getCacheKey()
    {
        return "custom_prefix:{$this->id}";
    }
    
  3. TTL Management: Set per-model TTL in the config or dynamically:

    Post::setCacheTTL(3600); // Override for 1 hour
    
  4. Cache Invalidation: The package auto-flushes cache on:

    • create(), update(), delete().
    • Use Cacheable::flushCache() manually if needed:
      Post::flushCache(); // Clears all Post cache entries
      

Integration Tips

  • Laravel 13+ Compatibility:

    • Tested with Laravel 13 and PHP 8.5. Ensure your project meets these requirements.
    • Use Cacheable::supportsLaravel13() to check compatibility in custom logic.
  • Cache Drivers: Supports Redis, Memcached, database, and file caching. Configure in .env:

    CACHE_DRIVER=redis
    
  • Query Complexity: Avoid caching overly complex queries (e.g., OR conditions). Use Cacheable::disableCache() for one-off queries:

    Post::disableCache()->whereRaw('...')->get();
    
  • Testing: Mock the cache in tests:

    $this->partialMock(Cache::class, ['get', 'put', 'forget']);
    
  • Laravel Events: Extend cache logic via events:

    Cacheable::addListener('beforeCache', function ($model, $query) {
        // Custom logic before caching
    });
    

Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • Default key generation uses class:query_hash. Complex queries (e.g., OR conditions) may produce identical hashes.
    • Fix: Override getCacheKey() or use Cacheable::setQueryHashStrategy('md5').
  2. Cache Stampede:

    • Concurrent requests may bypass cache if TTL expires during execution.
    • Fix: Increase TTL or use Cacheable::lockCache() for critical queries.
  3. Model Events:

    • Cache invalidation relies on Eloquent events (saved, deleted). Custom events may not trigger flushes.
    • Fix: Manually call flushCache() or bind to Cacheable::flushed event.
  4. Debugging:

    • Enable debug mode in config:
      'debug' => env('CACHEABLE_DEBUG', false),
      
    • Check logs for cache hits/misses and generated keys.
  5. PHP 8.5+ Type Safety:

    • Ensure your models and queries are compatible with PHP 8.5 strict types. Use declare(strict_types=1) in your models.
  6. whereNull() Edge Case:

    • Previously, whereNull() could trigger undefined array key errors. This is now fixed in v0.6.0.

Debugging Tips

  • Log Cache Keys:

    Cacheable::setDebug(true);
    

    Outputs keys to storage/logs/laravel.log (debug level).

  • Clear Cache:

    php artisan cache:clear
    

    Or manually:

    Cache::forget(Cacheable::getCacheKey($model));
    
  • Verify Cache:

    Cache::has(Cacheable::getCacheKey($model)); // Check existence
    Cache::get(Cacheable::getCacheKey($model)); // Inspect cached data
    

Extension Points

  1. Custom Cache Stores: Bind a custom cache store to the Cacheable service provider:

    CacheableServiceProvider::extend('custom', function () {
        return Cache::store('custom_driver');
    });
    
  2. Query Hashing: Override the hashing strategy:

    Cacheable::setQueryHashStrategy('sha256');
    
  3. Cache Tags: Use Laravel’s cache tags for bulk invalidation:

    Cacheable::tag(['posts', 'published']);
    Post::flushCache(); // Clears tags 'posts' and 'published'
    
  4. Conditional Caching: Disable caching for specific queries:

    Post::disableCache()->where('draft', true)->get();
    
  5. Laravel 13+ Features:

    • Leverage Laravel 13’s improved cache tagging or model events for tighter integration.
    • Example: Use Cacheable::listenForModelEvents() to hook into Laravel 13’s event system.

NO_UPDATE_NEEDED was not applicable due to meaningful updates.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle