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 Query Cache Laravel Package

neurony/laravel-query-cache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require neurony/laravel-query-cache
    

    Publish the config file:

    php artisan vendor:publish --provider="Neurony\QueryCache\QueryCacheServiceProvider"
    

    Update .env to use a compatible cache driver (e.g., REDIS_CACHE=redis).

  2. Enable Caching: Add the model to config/query-cache.php under models:

    'models' => [
        'App\Models\User' => [
            'cache_all' => true, // Cache all queries
            // OR
            'cache_duplicates' => true, // Cache only duplicates
        ],
    ],
    

    Or enable globally in config/query-cache.php:

    'cache_all' => true,
    
  3. First Use Case: Run a query on a cached model (e.g., User::all()). Subsequent identical queries will return cached results.


Implementation Patterns

Core Workflows

  1. Model-Specific Caching:

    • Use cache_all to cache every select query for a model (e.g., dashboard metrics).
    • Use cache_duplicates to cache only repeated queries (e.g., user profiles in loops).
  2. Query Tagging:

    • Cache keys are tagged by model class and query hash (e.g., model:App\Models\User:query:select*fromusers).
    • Clear cache per model:
      QueryCache::clear('App\Models\User');
      
  3. Integration with Eloquent:

    • Works seamlessly with where, with, orderBy, etc.:
      $users = User::where('active', true)->orderBy('name')->get(); // Cached if enabled
      
  4. Dynamic Model Registration:

    • Register models programmatically:
      QueryCache::enableForModel(User::class, ['cache_duplicates' => true]);
      
  5. Conditional Caching:

    • Disable caching for specific queries using a trait:
      use Neurony\QueryCache\Traits\DisableQueryCache;
      
      class UserController {
          use DisableQueryCache;
      
          public function sensitiveData() {
              $this->disableQueryCache();
              return User::where('secret', true)->get();
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Incompatible Cache Drivers:

    • Error: file or database drivers throw RuntimeException.
    • Fix: Use redis, memcached, or array (for testing only).
  2. Cache Key Collisions:

    • Issue: Complex queries (e.g., nested with) may generate identical hashes for different queries.
    • Workaround: Simplify queries or use cache_duplicates sparingly.
  3. TTL Management:

    • Default: 10 minutes (configurable via cache_ttl in config/query-cache.php).
    • Tip: Set shorter TTLs for volatile data (e.g., 1 minute for stock prices).
  4. Memory Usage:

    • Risk: Caching all queries for high-traffic models (e.g., Product) can bloat Redis.
    • Mitigation: Use cache_duplicates or exclude models with high query variance.
  5. Testing Quirks:

    • Problem: Cached queries persist across test runs.
    • Solution: Clear cache in setUp():
      public function setUp(): void {
          QueryCache::clearAll();
          parent::setUp();
      }
      

Debugging Tips

  1. Log Cache Hits/Misses: Enable debug mode in config:

    'debug' => env('QUERY_CACHE_DEBUG', false),
    

    Check Laravel logs for entries like:

    [QueryCache] Cache hit for App\Models\User (query: select * from users where active = ?)
    
  2. Inspect Cache Keys: Dump keys manually:

    $key = QueryCache::generateKey(User::class, User::query()->toSql());
    cache()->get($key);
    
  3. Bypass Cache Temporarily: Use the DisableQueryCache trait or environment flag:

    QUERY_CACHE_ENABLED=false
    

Extension Points

  1. Custom Cache Key Generation: Override the key generator in a service provider:

    QueryCache::setKeyGenerator(function ($model, $query) {
        return "custom:{$model}:{$query->toSql()}:".md5($query->getBindings());
    });
    
  2. Post-Cache Hooks: Listen for cache events (e.g., QueryCached):

    QueryCache::addListener('QueryCached', function ($model, $query, $cacheKey) {
        Log::info("Cached query for {$model} with key {$cacheKey}");
    });
    
  3. Conditional Caching Logic: Extend the QueryCache class to add rules (e.g., cache only during off-peak hours):

    QueryCache::shouldCache(function ($model, $query) {
        return now()->hour() < 8; // Cache only before 8 AM
    });
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge