PHP code example of mohammedjalal99 / filament-cache-plugin

1. Go to this page and download the library: Download mohammedjalal99/filament-cache-plugin library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mohammedjalal99 / filament-cache-plugin example snippets


// Get real-time metrics
FilamentCache::getMetrics();

// Returns: hit rate, response times, cache size, etc.

// Before: Slow resource with heavy queries
class OrderResource extends Resource
{
    protected static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with(['customer', 'items.product', 'payments'])
            ->withCount(['items', 'payments'])
            ->withSum('payments', 'amount');
    }
    
    public static function table(Table $table): Table
    {
        return $table->columns([
            TextColumn::make('total_revenue')
                ->getStateUsing(fn($record) => 
                    $record->calculateComplexRevenue() // Heavy calculation
                ),
        ]);
    }
}

// After: Lightning fast with zero config
class OrderResource extends Resource
{
    use CachesEverything; // 🚀 Add this trait
    
    protected static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with(['customer', 'items.product', 'payments'])
            ->withCount(['items', 'payments'])
            ->withSum('payments', 'amount')
            ->cached(600); // ⚡ Cache for 10 minutes
    }
    
    public static function table(Table $table): Table
    {
        return $table->columns([
            TextColumn::make('total_revenue')
                ->cached(fn($record) => 
                    $record->calculateComplexRevenue() // Now cached!
                ),
        ]);
    }
}



namespace App\Providers\Filament;

use Filament\Panel;
use Filament\PanelProvider;
use FilamentCache\FilamentCachePlugin;

class AdminPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {
        return $panel
            ->default()
            ->id('admin')
            ->path('admin')
            ->plugins([
                // Add the cache plugin
                FilamentCachePlugin::make(),
            ]);
    }
}



namespace App\Filament\Resources;

use Filament\Resources\Resource;
use FilamentCache\Concerns\CachesEverything;

class UserResource extends Resource
{
    use CachesEverything; // 🚀 Add this line
    
    // Your existing code stays the same!
    // Everything is now automatically cached
}

// Before: Slow query
protected static function getEloquentQuery(): Builder
{
    return parent::getEloquentQuery()
        ->with(['roles', 'profile', 'orders']);
}

// After: Cached query (10x faster!)
protected static function getEloquentQuery(): Builder
{
    return parent::getEloquentQuery()
        ->with(['roles', 'profile', 'orders'])
        ->cached(300); // Cache for 5 minutes
}

// Before: Database hit on every page load
Select::make('category_id')
    ->options(Category::pluck('name', 'id'))

// After: Cached options (instant loading!)
Select::make('category_id')
    ->cachedOptions('categories', fn() => 
        Category::pluck('name', 'id')
    )

// Before: Expensive calculation on every row
TextColumn::make('total_orders')
    ->getStateUsing(fn($record) => $record->orders()->count())

// After: Cached calculation (instant display!)
TextColumn::make('total_orders')
    ->cached(fn($record) => $record->orders()->count())



namespace App\Filament\Widgets;

use Filament\Widgets\StatsOverviewWidget;
use FilamentCache\Concerns\CachesWidgets;

class StatsWidget extends StatsOverviewWidget
{
    use CachesWidgets; // 🚀 Add this line
    
    protected function getStats(): array
    {
        // Cache expensive statistics
        return $this->cacheData([
            'total_users' => User::count(),
            'total_orders' => Order::count(),
            'revenue' => Order::sum('total'),
        ], ttl: 600); // Cache for 10 minutes
    }
}

return [
    'enabled' => true,
    
    // Cache duration (seconds)
    'ttl' => [
        'default' => 300,      // 5 minutes
        'queries' => 600,      // 10 minutes
        'navigation' => 1800,  // 30 minutes
        'widgets' => 300,      // 5 minutes
    ],
    
    // What to cache
    'cache' => [
        'pages' => true,       // Cache full pages
        'queries' => true,     // Cache database queries
        'navigation' => true,  // Cache navigation menu
        'widgets' => true,     // Cache dashboard widgets
        'forms' => true,       // Cache form options
    ],
    
    // Exclude specific routes from caching
    'exclude' => [
        'routes' => [
            'filament.admin.auth.*',
        ],
    ],
];

FilamentCachePlugin::make()
    // Basic Settings
    ->defaultTtl(600)                    // 10 minutes default
    ->enablePerformanceMonitoring()      // Track performance
    
    // Enable/Disable Features
    ->cachePages()                       // Cache full pages
    ->cacheQueries()                     // Cache DB queries
    ->cacheNavigation()                  // Cache navigation
    ->cacheWidgets()                     // Cache widgets
    ->cacheForms()                       // Cache form options
    
    // Advanced Settings
    ->useStore('redis')                  // Use Redis store
    ->enableTaggedCaching()              // Smart invalidation
    ->excludeRoutes(['admin.settings'])  // Skip specific routes
    ->maxCacheSize('100MB')              // Limit cache size

class OrderResource extends Resource
{
    use CachesEverything;
    
    protected static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with(['customer', 'items.product'])
            ->cached(300); // 5-minute cache
    }
    
    public static function table(Table $table): Table
    {
        return $table->columns([
            TextColumn::make('customer.name'),
            TextColumn::make('total_amount')
                ->cached(fn($record) => $record->calculateTotal()),
            TextColumn::make('profit_margin')
                ->cached(fn($record) => $record->calculateProfit()),
        ]);
    }
}

class AnalyticsWidget extends BaseWidget
{
    use CachesWidgets;
    
    protected function getViewData(): array
    {
        return $this->cacheData([
            'revenue_today' => Order::whereDate('created_at', today())->sum('total'),
            'orders_count' => Order::count(),
            'top_products' => Product::withCount('orderItems')->orderBy('order_items_count', 'desc')->limit(5)->get(),
        ], ttl: 900); // 15-minute cache
    }
}

// Force refresh by clearing specific cache
FilamentCache::forget('user_stats');

// Or disable caching temporarily
FilamentCachePlugin::make()->disable();

// In your Resource
class PostResource extends Resource
{
    protected static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->cached(300); // Cache for 5 minutes
    }
}

// Automatically cache dropdown options
Select::make('category_id')
    ->cachedOptions('categories', fn() => 
        Category::pluck('name', 'id')
    )

// In your Widget
class StatsWidget extends BaseWidget
{
    use CachesEverything;
    
    protected function getViewData(): array
    {
        return $this->cacheData([
            'total_users' => User::count(),
            'total_posts' => Post::count(),
            'revenue' => Order::sum('amount'),
        ], ttl: 600);
    }
}

// Cache expensive calculations
TextColumn::make('computed_score')
    ->cached(fn($record) => $record->calculateComplexScore())

// config/filament-cache.php
return [
    'enabled' => env('FILAMENT_CACHE_ENABLED', true),
    
    // Cache TTL (Time To Live)
    'ttl' => [
        'default' => 300,      // 5 minutes
        'queries' => 600,      // 10 minutes  
        'navigation' => 1800,  // 30 minutes
        'widgets' => 300,      // 5 minutes
        'forms' => 3600,       // 1 hour
    ],
    
    // Cache Stores
    'stores' => [
        'default' => 'redis',
        'pages' => 'redis',
        'queries' => 'database',
    ],
    
    // What to Cache
    'cache' => [
        'pages' => true,
        'queries' => true,
        'navigation' => true,
        'widgets' => true,
        'forms' => true,
        'tables' => true,
    ],
    
    // Performance Settings
    'performance' => [
        'monitor' => true,
        'log_slow_queries' => true,
        'preload_critical' => true,
    ],
    
    // Cache Keys
    'keys' => [
        'prefix' => 'filament_cache',
        'separator' => ':',
        'hash_keys' => true,
    ],
    
    // Exclusions
    'exclude' => [
        'routes' => [
            'filament.admin.auth.*',
            'filament.admin.pages.dashboard',
        ],
        'users' => [
            // User IDs to exclude from caching
        ],
        'ips' => [
            '127.0.0.1', // Exclude localhost
        ],
    ],
];

FilamentCachePlugin::make()
    // TTL Settings
    ->defaultTtl(600)
    ->queryTtl(1200)
    ->navigationTtl(3600)
    
    // Enable/Disable Features  
    ->cachePages()
    ->cacheQueries()
    ->cacheNavigation()
    ->cacheWidgets()
    ->cacheForms()
    ->cacheTables()
    
    // Or disable specific features
    ->disablePageCache()
    ->disableQueryCache()
    
    // Performance Options
    ->enablePerformanceMonitoring()
    ->enablePreloading()
    ->logSlowQueries(threshold: 1000)
    
    // Cache Stores
    ->useStore('redis')
    ->pagesStore('redis')
    ->queriesStore('database')
    
    // Exclusions
    ->excludeRoutes(['admin.settings.*'])
    ->excludeUsers([1, 2, 3])
    ->excludeIPs(['192.168.1.1'])
    
    // Advanced
    ->enableTaggedCaching()
    ->enableCompressionFor(['queries', 'pages'])
    ->maxCacheSize('100MB')

use FilamentCache\Concerns\CachesResources;

class UserResource extends Resource
{
    use CachesResources;
    
    // Auto-cache with relationships
    protected static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with(['profile', 'roles'])
            ->cached(ttl: 600, key: 'users_with_relations');
    }
    
    // Cache form schema
    public static function form(Form $form): Form
    {
        return $form->schema(
            static::cachedFormSchema('user_form', [
                TextInput::make('name'),
                Select::make('role_id')
                    ->cachedOptions('user_roles', fn() => 
                        Role::pluck('name', 'id')
                    ),
            ])
        );
    }
    
    // Cache table columns
    public static function table(Table $table): Table
    {
        return $table->columns(
            static::cachedTableColumns('user_table', [
                TextColumn::make('name'),
                TextColumn::make('posts_count')
                    ->cached(fn($record) => $record->posts()->count()),
            ])
        );
    }
}

use FilamentCache\Concerns\CachesWidgets;

class AnalyticsWidget extends BaseWidget
{
    use CachesWidgets;
    
    protected static string $view = 'widgets.analytics';
    
    // Cache expensive analytics data
    protected function getViewData(): array
    {
        return $this->cacheWidgetData([
            'visitors' => $this->getCachedVisitors(),
            'revenue' => $this->getCachedRevenue(),
            'conversion' => $this->getCachedConversion(),
        ]);
    }
    
    private function getCachedVisitors(): int
    {
        return $this->remember('visitors_count', function () {
            return Analytics::visitors()
                ->whereBetween('date', [now()->subDays(30), now()])
                ->sum('count');
        }, ttl: 3600);
    }
    
    private function getCachedRevenue(): float
    {
        return $this->remember('revenue_total', function () {
            return Order::where('status', 'completed')
                ->whereBetween('created_at', [now()->subDays(30), now()])
                ->sum('total');
        }, ttl: 1800);
    }
}

use FilamentCache\Concerns\CachesPages;

class CustomPage extends Page
{
    use CachesPages;
    
    // Conditional caching
    protected function shouldCache(): bool
    {
        return auth()->user()->cannot('bypass_cache') 
            && !request()->has('fresh');
    }
    
    // Dynamic cache keys
    protected function getCacheKey(): string
    {
        return sprintf(
            'page_%s_user_%d_locale_%s',
            static::class,
            auth()->id(),
            app()->getLocale()
        );
    }
    
    // Cache with user-specific data
    protected function getViewData(): array
    {
        return $this->cachePageData([
            'user_stats' => $this->getUserStats(),
            'recent_activity' => $this->getRecentActivity(),
        ]);
    }
}

// Automatically tag caches by model
User::cached(['users', 'profile'])->get();

// Clear all user-related caches when user updates
// Automatically handled by the plugin!

// View cache performance in real-time
FilamentCache::getMetrics();

// Returns:
[
    'hit_rate' => 94.5,
    'miss_rate' => 5.5,  
    'total_requests' => 1250,
    'cache_hits' => 1181,
    'cache_misses' => 69,
    'average_response_time' => 0.23,
    'cache_size' => '45.2MB',
    'top_cached_queries' => [...],
]

// Warm up critical caches
php artisan filament-cache:warm

// Warm specific resources
php artisan filament-cache:warm --resource=UserResource --resource=PostResource

// Schedule cache warming
// In Console/Kernel.php
$schedule->command('filament-cache:warm')->hourly();

// Debug mode - see what's being cached
FilamentCachePlugin::make()->debug();

// Cache analytics dashboard
php artisan filament-cache:analyze

// Clear specific caches
php artisan filament-cache:clear --tags=users,posts
php artisan filament-cache:clear --pattern="user_*"

// Check if Redis is running
php artisan cache:clear
redis-cli ping

// Enable debug mode
FilamentCachePlugin::make()->debug()
  
// Configure cache invalidation
FilamentCache::invalidateOnUpdate([User::class, Post::class]);

// Manual invalidation
FilamentCache::forget('user_stats');
FilamentCache::forgetByTags(['users']);

// Optimize cache size
FilamentCachePlugin::make()
    ->maxCacheSize('50MB')
    ->enableCompression()

// Create custom cache driver
class MyCustomCacheDriver implements CacheDriverInterface
{
    public function get(string $key): mixed
    {
        // Custom logic
    }
    
    public function put(string $key, mixed $value, int $ttl): void
    {
        // Custom logic  
    }
}

// Register custom driver
FilamentCachePlugin::make()
    ->extend('custom', MyCustomCacheDriver::class)
    ->useStore('custom');

FilamentCachePlugin::make()
    ->cacheKeyGenerator(function ($context) {
        return sprintf(
            '%s:%s:%s:%s',
            $context['type'],
            $context['model'],
            auth()->id(),
            app()->getLocale()
        );
    });

// Listen to cache events
FilamentCache::listen('cache:hit', function ($key, $value) {
    Log::info("Cache hit: {$key}");
});

FilamentCache::listen('cache:miss', function ($key) {
    Log::info("Cache miss: {$key}");
});

FilamentCache::listen('cache:write', function ($key, $value, $ttl) {
    Log::info("Cache write: {$key} (TTL: {$ttl}s)");
});
bash
php artisan vendor:publish --tag=filament-cache-config
bash
# Check Redis connection
redis-cli ping

# Clear all caches
php artisan cache:clear
php artisan config:clear

# Check cache driver
php artisan tinker
>>> cache()->getStore()
bash
php artisan vendor:publish --tag=filament-cache-config