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

Laracache Laravel Package

mostafaznv/laracache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mostafaznv/laracache
    
  2. Publish Config (optional):

    php artisan vendor:publish --provider="Mostafaznv\Laracache\LaracacheServiceProvider"
    
    • Defaults are sensible, but publishing allows customization of:
      • Cache driver (cache.driver in .env)
      • Default TTL (in config/laracache.php)
      • Event hooks (e.g., created, updated, deleted)
  3. First Use Case: Cache a model's find() or first() query by adding the Cacheable trait to your model:

    use Mostafaznv\Laracache\Traits\Cacheable;
    
    class User extends Model
    {
        use Cacheable;
    
        protected $cacheEntity = [
            'name' => 'user:123', // Dynamic key (use `{id}` for model ID)
            'ttl'  => 60,          // 60 seconds
        ];
    }
    
    • Trigger cache: Call User::find(123) or User::first(). The package auto-caches results on retrieved events.

Implementation Patterns

Core Workflows

  1. Dynamic Cache Keys: Use placeholders like {id}, {slug}, or {email} in $cacheEntity['name']:

    protected $cacheEntity = [
        'name' => 'user:{email}:profile',
        'ttl'  => 300,
    ];
    
    • Automatically resolves to user:john@example.com:profile for User::findByEmail('john@example.com').
  2. Conditional Caching: Override getCacheKey() to dynamically adjust keys/TTL:

    public function getCacheKey()
    {
        if ($this->isPremium()) {
            return ['name' => 'user:premium:{id}', 'ttl' => 86400];
        }
        return $this->cacheEntity;
    }
    
  3. Bulk Operations: Cache collections with CacheableCollection trait:

    class UserCollection extends Collection
    {
        use \Mostafaznv\Laracache\Traits\CacheableCollection;
    
        protected $cacheEntity = [
            'name' => 'users:active',
            'ttl'  => 1800,
        ];
    }
    
    • Cache is invalidated when any model in the collection is updated/deleted.
  4. Event-Based Invalidation: Extend cache invalidation to custom events:

    // In a service or observer
    event(new UserProfileUpdated($user));
    
    // In User model
    protected static function getCacheEvents()
    {
        return [
            'created', 'updated', 'deleted',
            'user.profile.updated', // Custom event
        ];
    }
    
  5. Fallback Logic: Use shouldCache() to skip caching for specific cases:

    protected function shouldCache()
    {
        return !request()->has('nocache');
    }
    

Integration Tips

  • APIs: Pair with Laravel's API resources to cache serialized responses:
    public function toArray($request)
    {
        return Cache::remember("user:{$this->id}:api", now()->addMinutes(5), function() {
            return parent::toArray($request);
        });
    }
    
  • Queues: Combine with Laravel Queues to cache results of long-running jobs:
    $user = Cache::remember("user:{$id}:job:{$jobId}", now()->addHours(1), function() use ($id) {
        return User::find($id);
    });
    
  • Testing: Mock cache behavior in tests:
    Cache::shouldReceive('get')->andReturn($mockedUser);
    

Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • Issue: Overlapping dynamic keys (e.g., user:{id} vs. user:{email}) may cause unintended cache hits.
    • Fix: Use unique prefixes or namespaces:
      'name' => 'user.by_id:{id}', 'user.by_email:{email}'
      
  2. TTL Granularity:

    • Issue: Static TTLs may lead to stale data or excessive cache churn.
    • Fix: Use getCacheTTL() to dynamically adjust:
      protected function getCacheTTL()
      {
          return $this->isActive() ? 3600 : 60; // 1h for active, 1m for inactive
      }
      
  3. Event Hooks:

    • Issue: Forgetting to include deleted in getCacheEvents() leaves orphaned cache entries.
    • Fix: Always include CRUD events unless intentional:
      protected static function getCacheEvents()
      {
          return ['created', 'updated', 'deleted'];
      }
      
  4. Memory Leaks:

    • Issue: Unbounded cache growth from dynamic keys (e.g., {timestamp}).
    • Fix: Limit TTL or use a cache prefixer:
      'name' => 'user:{id}:{timestamp}', // Risky!
      'name' => 'user:{id}',             // Safer
      
  5. Race Conditions:

    • Issue: Concurrent created/updated events may overwrite cache.
    • Fix: Use Cache::lock() for critical sections:
      Cache::lock("user:{$id}:update", 5)->block(function() {
          // Safe update logic
      });
      

Debugging

  • Cache Inspection: Use Tinker to inspect cached keys:

    php artisan tinker
    >>> Cache::keys('user:*')->contains('user:123');
    
  • Logging: Enable debug mode in config/laracache.php:

    'debug' => env('APP_DEBUG', false),
    
    • Logs cache hits/misses to storage/logs/laracache.log.
  • Manual Invalidation: Force-invalidate a cache key:

    Cache::forget('user:123');
    

Extension Points

  1. Custom Cache Drivers: Bind a custom driver in AppServiceProvider:

    Cache::extend('redis_cluster', function() {
        return Cache::repository(new RedisClusterStore());
    });
    

    Then configure in .env:

    CACHE_DRIVER=redis_cluster
    
  2. Cache Tags: Add tag-based invalidation (requires illuminate/cache v8.50+):

    protected $cacheTags = ['users', 'premium_users'];
    

    Invalidate by tag:

    Cache::tags(['users'])->flush();
    
  3. Cache Warmers: Pre-load caches during deployment:

    php artisan cache:warm
    
    • Define warmers in app/Console/Kernel.php:
      protected function warmCache()
      {
          Cache::put('homepage', Homepage::with('stats')->first());
      }
      
  4. Cache Versioning: Append a version to keys to invalidate all caches on config changes:

    'name' => 'user:{id}:v' . config('cache.version'),
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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