diff --git a/src/SelectTree.php b/src/SelectTree.php index f6cb706..6060905 100644 --- a/src/SelectTree.php +++ b/src/SelectTree.php @@ -18,6 +18,7 @@ use Filament\Support\Facades\FilamentIcon; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Support\Arr; use Illuminate\Support\Collection; class SelectTree extends Field implements HasAffixActions @@ -103,16 +104,19 @@ protected function setUp(): void // Check if the component's relationship is a BelongsToMany relationship. if ($component->getRelationship() instanceof BelongsToMany) { // Wrap the state in a collection and convert it to an array if it's not set. - $state = Collection::wrap($state ?? []); + $state = Arr::wrap($state ?? []); - if($pivotData = $component->getPivotData()) { - $component->getRelationship()->syncWithPivotValues($state->toArray(), $pivotData); - + $pivotData = $component->getPivotData(); + + // Sync the relationship with the provided state (IDs). + if ($pivotData === []) { + $component->getRelationship()->sync($state ?? []); + return; } - // Sync the relationship with the provided state (IDs). - $component->getRelationship()->sync($state->toArray()); + // Sync the relationship with the provided state (IDs) plus pivot data. + $component->getRelationship()->syncWithPivotValues($state ?? [], $pivotData); } });