PHPackages                             skaisser/laravel-cache-cascade - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. skaisser/laravel-cache-cascade

ActiveLibrary[Caching](/categories/caching)

skaisser/laravel-cache-cascade
==============================

A Laravel package for multi-layer caching with automatic fallback, visitor isolation, and database seeding support

v1.2.1(10mo ago)68MITPHPPHP ^8.1CI passing

Since Jun 24Pushed 10mo agoCompare

[ Source](https://github.com/skaisser/laravel-cache-cascade)[ Packagist](https://packagist.org/packages/skaisser/laravel-cache-cascade)[ RSS](/packages/skaisser-laravel-cache-cascade/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (5)Used By (0)

Laravel Cache Cascade
=====================

[](#laravel-cache-cascade)

[![Tests](https://github.com/skaisser/laravel-cache-cascade/actions/workflows/tests.yml/badge.svg)](https://github.com/skaisser/laravel-cache-cascade/actions/workflows/tests.yml)[![Code Coverage](https://camo.githubusercontent.com/6c38d4b0828818953497e6a46fb1b20cf8130949593f9cb1ae8545b1861fa9e9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d39302e31332532352d627269676874677265656e2e737667)](https://github.com/skaisser/laravel-cache-cascade)[![Laravel](https://camo.githubusercontent.com/c5636cbc00edeb2fc30bc0a089aca31231cc9b87845c6d56b74fb9e2fc931b02/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e7825323025374325323031312e7825323025374325323031322e782d4646324432303f7374796c653d666c61742d737175617265266c6f676f3d6c61726176656c)](https://laravel.com)

**Never lose your cached data again.** Laravel Cache Cascade provides bulletproof caching with automatic fallback through multiple storage layers. When Redis goes down, your app keeps running. When files get corrupted, data loads from the database. When the database is empty, seeders run automatically.

🚀 **Perfect for**: SaaS settings, CMS content, API responses, feature flags, and any rarely-changing data that must always be available.

Why This Package Exists
-----------------------

[](#why-this-package-exists)

Ever had Redis crash and take your app down because all your cached settings disappeared? Or struggled with cache invalidation when your database updates? Laravel's built-in cache is great, but it has limitations:

- **Single point of failure** - When your cache driver fails, your app fails
- **No automatic persistence** - Cache expires and you have to rebuild from scratch
- **Manual invalidation** - Database changes don't automatically update the cache
- **No built-in fallback** - You need to write try-catch blocks everywhere

**Laravel Cache Cascade solves these problems** by creating a resilient caching system that automatically falls back through multiple storage layers and keeps them in sync.

Laravel Cache vs Cache Cascade
------------------------------

[](#laravel-cache-vs-cache-cascade)

FeatureLaravel CacheCache Cascade**Fallback Mechanism**❌ None✅ Cache → File → Database → Seeder**Automatic Invalidation**❌ Manual✅ Model observers auto-refresh**Persistent Storage**❌ Memory only✅ File + Memory**Database Sync**❌ Manual✅ Automatic on update**Visitor Isolation**❌ Not built-in✅ Optional per-key**Auto-seeding**❌ Manual✅ Runs seeders automatically**Zero-config Models**❌ Requires setup✅ Just add traitFeatures
--------

[](#features)

- **🏗️ Multi-layer Caching**: Automatic fallback chain (Cache → File → Database → Auto-seeding)
- **🔒 Visitor Isolation**: Optional visitor-specific cache keys for enhanced security
- **🌱 Auto-seeding**: Automatically seed data from seeders when not found
- **📁 File Storage**: Persistent file-based caching layer
- **🔄 Flexible Configuration**: Customize fallback order and behavior
- **🏷️ Cache Tagging**: Support for tagged cache operations
- **⚡ High Performance**: Request-level caching to minimize database queries
- **♻️ Automatic Invalidation**: Database changes automatically refresh cache and file layers
- **🎯 Model Integration**: Trait for automatic cache management in Eloquent models

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require skaisser/laravel-cache-cascade
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=cache-cascade-config
```

This will create a `config/cache-cascade.php` file where you can customize the package settings.

### Key Configuration Options

[](#key-configuration-options)

```
return [
    // Path for file-based cache storage
    'config_path' => 'config/dynamic',

    // Cache settings
    'cache_prefix' => 'cascade:',
    'default_ttl' => 86400, // 24 hours

    // Enable visitor-specific caching
    'visitor_isolation' => false,

    // Database integration
    'use_database' => true,
    'auto_seed' => true,

    // Define fallback order
    'fallback_chain' => ['cache', 'file', 'database'],
];
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use Skaisser\CacheCascade\Facades\CacheCascade;

// Get data with automatic fallback
$data = CacheCascade::get('settings', []);

// Get with custom options
$faqs = CacheCascade::get('faqs', [], [
    'ttl' => 3600, // 1 hour
    'transform' => fn($data) => collect($data)->sortBy('order')
]);

// Set data (updates all layers)
CacheCascade::set('settings', $data);

// Clear specific cache (both methods work)
CacheCascade::clearCache('settings');
CacheCascade::forget('settings'); // Laravel-style alias

// Using the global helper
$settings = cache_cascade('settings', []); // Get with default
$value = cache_cascade('key', function() {  // Remember pattern
    return expensive_operation();
});
```

### Remember Pattern

[](#remember-pattern)

```
// Cache data with a callback (original method)
$users = CacheCascade::remember('active-users', function() {
    return User::where('active', true)->get();
}, 3600); // Cache for 1 hour

// Laravel-compatible signature with rememberFor()
$posts = CacheCascade::rememberFor('recent-posts', 3600, function() {
    return Post::recent()->limit(10)->get();
});

// Using the helper function
$data = cache_cascade('expensive-data', function() {
    return expensive_computation();
});
```

### Visitor Isolation

[](#visitor-isolation)

Enable visitor-specific caching to prevent data leakage between users:

```
// Enable for specific cache
$userData = CacheCascade::get('user-settings', [], [
    'visitor_isolation' => true
]);

// Or use remember with isolation
$userDashboard = CacheCascade::remember('dashboard', function() {
    return $this->generateDashboard();
}, 3600, true); // Last parameter enables visitor isolation
```

### Working with Models

[](#working-with-models)

The package can automatically load data from Eloquent models and seed if empty:

```
// If 'faqs' table is empty, it will run FaqSeeder automatically
$faqs = CacheCascade::get('faqs');

// The package will look for:
// 1. Cache key 'cascade:faqs'
// 2. File at 'config/dynamic/faqs.php'
// 3. App\Models\Faq::orderBy('order')->get()
// 4. Database\Seeders\FaqSeeder (if auto_seed is enabled)
```

How It Works
------------

[](#how-it-works)

### Fallback Chain

[](#fallback-chain)

When you request data, the package tries each storage layer in order:

1. **Cache Layer**: Fast in-memory storage (Redis/Memcached)
2. **File Layer**: Persistent file storage for rarely-changing data
3. **Database Layer**: Load from Eloquent models
4. **Auto-seeding**: Run seeders if no data exists

### File Storage Format

[](#file-storage-format)

Files are stored in PHP format by default:

```
// config/dynamic/settings.php
