<?php
namespace App\Filament\Fields;
use App\Models\Filter;
use Filament\Forms\Components\Select;
use Illuminate\Database\Eloquent\Builder;
class TagSelect extends Select
{
public function setUp(): void
{
parent::setUp();
$this->multiple()
->searchable()
->relationship('filters', 'name', fn (Builder $query) => $query->tag())
->loadStateFromRelationshipsUsing(function (Select $component, $state): void {
if (filled($state)) {
return;
}
$relationship = $component->getRelationship();
$relatedModels = $relationship->where('type', 'tag')->getResults();
$component->state(
$relatedModels
->pluck($relationship->getRelatedKeyName())
->map(static fn ($key): string => strval($key))
->toArray(),
);
})
->saveRelationshipsUsing(function (Select $component, $state) {
$relationship = $component->getRelationship();
$allTagFilters = Filter::where('type', 'tag')->pluck('id');
$relationship->detach($allTagFilters);
$relationship->attach($state);
});
}
}