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

eusonlito/laravel-database-cache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require eusonlito/laravel-database-cache
    

    Publish the config file:

    php artisan vendor:publish --provider="Eusonlito\DatabaseCache\DatabaseCacheServiceProvider" --tag="config"
    
  2. Basic Configuration Edit config/database-cache.php to define:

    'enabled' => env('DATABASE_CACHE_ENABLED', true),
    'cache_driver' => env('DATABASE_CACHE_DRIVER', 'database'),
    'cache_prefix' => 'db_cache_',
    'ttl' => 60, // Default TTL in seconds
    
  3. First Use Case Cache a simple Eloquent query:

    use Eusonlito\DatabaseCache\Facades\DatabaseCache;
    
    $users = DatabaseCache::remember('users.active', 300, function () {
        return User::where('active', true)->get();
    });
    

Key Files to Review

  • config/database-cache.php – Configuration options.
  • src/Facades/DatabaseCache.php – Main facade for caching queries.
  • src/Traits/DatabaseCacheTrait.php – Eloquent model trait for caching.

Implementation Patterns

Core Workflows

1. Facade-Based Caching

Use the facade for ad-hoc caching:

// Cache a query for 1 hour
$posts = DatabaseCache::remember('posts.featured', 3600, function () {
    return Post::where('featured', true)->with('author')->get();
});

2. Eloquent Model Trait

Attach the trait to models for automatic caching:

use Eusonlito\DatabaseCache\Traits\DatabaseCacheTrait;

class User extends Model
{
    use DatabaseCacheTrait;

    protected $cacheKey = 'users';
}

Now, queries like User::all() will cache results under users.all.

3. Query Builder Integration

Cache raw query builder results:

$results = DatabaseCache::remember('products.in_stock', 1800, function () {
    return DB::table('products')->where('stock', '>', 0)->get();
});

4. Dynamic Cache Keys

Use closures or dynamic keys for context-aware caching:

$cacheKey = "reports.sales.{$year}";
$report = DatabaseCache::remember($cacheKey, 3600, function () use ($year) {
    return Report::whereYear('created_at', $year)->sum('revenue');
});

Integration Tips

Cache Invalidation

Manually clear cached queries:

DatabaseCache::forget('users.active');
DatabaseCache::clear(); // Clears all cached queries

Conditional Caching

Skip caching in development:

if (app()->environment('production')) {
    $data = DatabaseCache::remember('...', 3600, $callback);
} else {
    $data = $callback();
}

Cache Tags (Advanced)

Use tags for bulk invalidation (requires custom implementation):

// Example: Tag-based invalidation (extend the package)
DatabaseCache::tag(['users', 'active'])->remember('...', ...);

Fallback Logic

Handle cache misses gracefully:

$data = DatabaseCache::remember('expensive_query', 3600, function () {
    return DB::table('large_table')->get();
}, function () {
    return collect(); // Fallback empty collection
});

Gotchas and Tips

Pitfalls

1. Cache Key Collisions

  • Issue: Two different queries might use the same cache key (e.g., User::all() and User::query()->get()).
  • Fix: Use unique keys or extend the trait to generate keys dynamically:
    protected function getCacheKey()
    {
        return "users.{$this->getQuery()->toSql()}";
    }
    

2. Stale Data in Development

  • Issue: Caching in local environment can hide query changes.
  • Fix: Disable caching in non-production environments:
    'enabled' => app()->environment('production'),
    

3. Memory Overhead

  • Issue: Caching large datasets (e.g., User::all()) can bloat memory.
  • Fix: Use pagination or chunking:
    $users = DatabaseCache::remember('users.paginated', 3600, function () {
        return User::paginate(50);
    });
    

4. Eloquent Relationships

  • Issue: Cached models may not load relationships lazily.
  • Fix: Eager-load relationships in the cache callback:
    $users = DatabaseCache::remember('users.with_roles', 3600, function () {
        return User::with('roles')->get();
    });
    

5. Database Locking

  • Issue: Concurrent writes to the same cache key can cause race conditions.
  • Fix: Use cache_lock or database driver with transactions:
    'cache_driver' => 'database', // Uses DB transactions
    

Debugging Tips

1. Verify Cache Hits/Misses

Enable logging in config/database-cache.php:

'log_enabled' => true,

Check storage/logs/laravel.log for cache events.

2. Inspect Cache Storage

Query the cache table directly:

SELECT * FROM cache WHERE key LIKE 'db_cache_%';

3. Clear Cache Programmatically

Use Artisan commands or facade:

php artisan cache:clear

Or:

DatabaseCache::clear();

4. Override TTL per Query

Set custom TTL for specific queries:

DatabaseCache::remember('volatile_data', 60, $callback); // 1-minute TTL

Extension Points

1. Custom Cache Drivers

Extend the package to support Redis or Memcached:

// config/database-cache.php
'cache_driver' => 'redis',

Ensure the driver is configured in config/cache.php.

2. Hook into Cache Events

Publish the package’s event handlers:

php artisan vendor:publish --provider="Eusonlito\DatabaseCache\DatabaseCacheServiceProvider" --tag="events"

Listen for DatabaseCacheStored and DatabaseCacheMissed events.

3. Add Cache Metadata

Store additional metadata (e.g., query hash, timestamp):

DatabaseCache::remember('data', 3600, $callback, [], [
    'query_hash' => md5($callback->toSql())
]);

4. Integrate with Laravel Scout

Cache search results:

$searchResults = DatabaseCache::remember("search:{$query}", 3600, function () use ($query) {
    return Product::search($query)->get();
});

5. Async Cache Population

Use Laravel Queues to populate cache in the background:

DatabaseCache::dispatch('expensive_query', 86400, $callback);
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony