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

Lada Cache Laravel Package

spiritix/lada-cache

Redis-based, fully automated query cache for Laravel. Transparent with Eloquent/Query Builder, granular invalidation of affected rows/tables, scalable and cluster-ready. Includes Debugbar insights and table include/exclude controls.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require spiritix/lada-cache
    php artisan vendor:publish --provider="Spiritix\LadaCache\LadaCacheServiceProvider"
    
  2. Enable in .env:
    LADA_CACHE_ACTIVE=true
    LADA_CACHE_DEBUGBAR=true  # Optional (for Debugbar integration)
    
  3. Add Trait to Models: Extend a base model or add use Spiritix\LadaCache\Database\LadaCacheTrait; to all Eloquent models.

First Use Case

  • Automatic Caching: After setup, all Eloquent/Query Builder queries are cached transparently.
    // Automatically cached
    $users = User::where('active', true)->get();
    
  • Debugging: Use Debugbar to inspect cache hits/misses/invalidations.

Implementation Patterns

Core Workflow

  1. Transparent Integration:

    • Lada intercepts queries via a custom Connection subclass (registered via DB::extend()).
    • No manual cache calls needed—queries are cached automatically.
  2. Granular Control:

    • Exclude Tables: Configure in config/lada-cache.php:
      'exclude_tables' => ['sensitive_data', 'logs'],
      
    • Per-Query Bypass:
      User::withoutCache()->where('id', 1)->first(); // Skips cache
      
  3. Invalidation:

    • Automatic: Inserts/updates/deletes invalidate only affected rows/tables.
    • Manual: Use php artisan lada-cache:flush or Cache::flush().
  4. Multi-Connection Support:

    • Works with named connections (e.g., DB::connection('mysql2')) if models specify $connection.

Advanced Patterns

  • Debugbar Integration: Visualize cache metrics (hits/misses/invalidations) in Debugbar.

    // Enable in config/lada-cache.php
    'debugbar' => [
        'enabled' => env('LADA_CACHE_DEBUGBAR', false),
    ],
    
  • Custom Redis Connection: Use a non-default Redis connection:

    'redis_connection' => 'custom_redis',
    
  • Base Model Approach:

    // app/Models/BaseModel.php
    use Spiritix\LadaCache\Database\LadaCacheTrait;
    
    abstract class BaseModel extends Model {
        use LadaCacheTrait;
    }
    
  • Bulk Operations: Lada handles insertUsing, updateFrom, and truncate invalidations automatically.


Gotchas and Tips

Pitfalls

  1. Composite Primary Keys:

    • Row-level invalidation falls back to table-level if the primary key isn’t a single column.
    • Fix: Ensure models use simple primary keys or whitelist tables for table-level invalidation.
  2. Raw SQL Bypasses Cache:

    • Queries via DB::select(), DB::statement(), or raw PDO are not cached.
    • Workaround: Use Eloquent/Query Builder for cached queries.
  3. Debugbar Conflicts:

    • If Debugbar isn’t installed, disable it in config:
      'debugbar' => ['enabled' => false],
      
  4. Connection Issues:

    • Lada’s Connection subclass may conflict with third-party packages overriding DB::extend().
    • Fix: Ensure Lada’s provider runs last in config/app.php under providers.
  5. Locking Bypasses Cache:

    • lockForUpdate()/sharedLock() queries skip caching (pessimistic locks).

Debugging Tips

  • Cache Key Collisions: Use LADA_CACHE_DEBUG_KEYS=true in .env to log generated keys (helpful for diagnosing collisions).
  • Invalidation Delays: Check Redis for stale tags with:
    redis-cli --scan --pattern "*:lada:*"
    
  • Performance Bottlenecks: Monitor Debugbar’s "Lada Cache" panel for slow queries or high miss rates.

Extension Points

  1. Custom Reflector: Override the SQL reflector to handle edge cases (e.g., complex UNION queries):

    // app/Providers/AppServiceProvider.php
    use Spiritix\LadaCache\Reflector\QueryReflector;
    
    public function register() {
        $this->app->bind(QueryReflector::class, function () {
            return new CustomQueryReflector();
        });
    }
    
  2. Cache Key Customization: Extend the key generator:

    // app/Providers/AppServiceProvider.php
    use Spiritix\LadaCache\Cache\CacheKeyGenerator;
    
    public function register() {
        $this->app->bind(CacheKeyGenerator::class, function () {
            return new CustomCacheKeyGenerator();
        });
    }
    
  3. Post-Invalidation Hooks: Listen for invalidation events:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \Spiritix\LadaCache\Events\CacheInvalidated::class => [
            \App\Listeners\LogInvalidation::class,
        ],
    ];
    

Configuration Quirks

  • Expiration Time: Set globally in config or per-table:
    'expiration' => 60, // Default: 60 seconds
    'table_expiration' => [
        'sessions' => 300, // 5 minutes
    ],
    
  • Redis Connection: Ensure the Redis connection (lada-cache.redis_connection) is properly configured in config/database.php.

Performance Tuning

  • Large Payloads: Avoid caching queries returning >100MB of data (Redis serialization overhead).
  • High Miss Rates: Shorten expiration for volatile data or adjust include_tables to exclude rarely accessed tables.
  • Cluster Setups: Use Redis Cluster with predis/predis or phpredis for horizontal scaling.

```markdown
### Pro Tips for Daily Use
1. **Cache Warming**:
   Pre-load critical queries during deployment:
   ```php
   // In a deploy script
   User::where('is_admin', true)->cached()->get(); // Forces cache population
  1. Tag-Based Invalidation: Manually invalidate specific tags (e.g., after bulk imports):

    Cache::tags(['users'])->flush();
    
  2. Temporary Disabling: Disable cache during migrations or testing:

    php artisan lada-cache:disable
    # ... run migrations ...
    php artisan lada-cache:enable
    
  3. Debugging Stale Data: Force a cache miss for a specific query:

    User::withoutCache()->where('id', 1)->first();
    
  4. Monitoring: Track cache efficiency with:

    php artisan lada-cache:stats
    

    (Add this to your Artisan commands if missing.)

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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope