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
}
// 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
}
}
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!