diff --git a/app/Filament/Filters/ResourceTreeFilter.php b/app/Filament/Filters/ResourceTreeFilter.php index 28c8aea..a713c22 100644 --- a/app/Filament/Filters/ResourceTreeFilter.php +++ b/app/Filament/Filters/ResourceTreeFilter.php @@ -5,9 +5,11 @@ namespace App\Filament\Filters; use App\Models\Resource\Category; +use Cache; use Closure; use Filament\Forms\Components\Select; use Filament\Tables\Filters\BaseFilter; +use Illuminate\Database\Eloquent\Builder; class ResourceTreeFilter extends BaseFilter { @@ -29,9 +31,13 @@ protected function setUp(): void { parent::setUp(); - $categories = Category::query() - ->with('subcategories.types') - ->get(); + $categories = Cache::driver('array') + ->rememberForever( + 'resource-tree-filter-categories', + fn () => Category::query() + ->with('subcategories.types') + ->get() + ); $this->form(fn () => [ Select::make('category') @@ -61,6 +67,18 @@ protected function setUp(): void ->pluck('name', 'id') ) ->hidden(fn (Select $component) => empty($component->getOptions())), - ]); + ]) + ->query(function (Builder $query, array $data) use ($categories) { + $subcategory = $categories->firstWhere('id', $data['category']) + ?->subcategories + ->firstWhere('id', $data['subcategory']); + + $type = $subcategory?->types + ->firstWhere('id', $data['type']); + + return $query->when($data['category'], fn (Builder $query, $value) => $query->where('category_id', $value)) + ->when($subcategory?->id, fn (Builder $query, $value) => $query->where('subcategory_id', $value)) + ->when($type?->id, fn (Builder $query, $value) => $query->whereRelation('types', 'type_id', $value)); + }); } } diff --git a/app/Filament/Resources/OrganisationResource/RelationManagers/ResourcesRelationManager.php b/app/Filament/Resources/OrganisationResource/RelationManagers/ResourcesRelationManager.php index 1e76db5..ca65852 100644 --- a/app/Filament/Resources/OrganisationResource/RelationManagers/ResourcesRelationManager.php +++ b/app/Filament/Resources/OrganisationResource/RelationManagers/ResourcesRelationManager.php @@ -4,6 +4,7 @@ namespace App\Filament\Resources\OrganisationResource\RelationManagers; +use App\Filament\Filters\ResourceTreeFilter; use App\Filament\Forms\FieldGroups; use App\Filament\Resources\ResourceResource; use App\Filament\Tables\Actions\ExportAction; @@ -145,22 +146,14 @@ public static function table(Table $table): Table ->toggleable(), ]) ->filters([ - SelectFilter::make('category') - ->label(__('resource.fields.category')) - ->relationship('category', 'name'), - - SelectFilter::make('subcategory') - ->relationship('subcategory', 'name') - ->label(__('resource.fields.subcategory')), - - SelectFilter::make('type') - ->label(__('resource.fields.type')) - ->relationship('types', 'name'), - SelectFilter::make('county') ->label(__('general.county')) ->relationship('county', 'name'), + ResourceTreeFilter::make('cat') + ->columns(3) + ->columnSpan(3), + ]) ->headerActions([ ExportAction::make(),