1010use Filament \Forms \Components \Concerns \CanBeSearchable ;
1111use Filament \Forms \Components \Concerns \HasActions ;
1212use Filament \Forms \Components \Concerns \HasAffixes ;
13+ use Filament \Forms \Components \Concerns \HasPivotData ;
1314use Filament \Forms \Components \Concerns \HasPlaceholder ;
1415use Filament \Forms \Components \Contracts \HasAffixActions ;
1516use Filament \Forms \Components \Field ;
1617use Filament \Forms \Form ;
1718use Filament \Support \Facades \FilamentIcon ;
1819use Illuminate \Database \Eloquent \Relations \BelongsTo ;
1920use Illuminate \Database \Eloquent \Relations \BelongsToMany ;
21+ use Illuminate \Support \Arr ;
2022use Illuminate \Support \Collection ;
2123
2224class SelectTree extends Field implements HasAffixActions
@@ -26,6 +28,7 @@ class SelectTree extends Field implements HasAffixActions
2628 use HasActions;
2729 use HasAffixes;
2830 use HasPlaceholder;
31+ use HasPivotData;
2932
3033 protected string $ view = 'select-tree::select-tree ' ;
3134
@@ -101,10 +104,19 @@ protected function setUp(): void
101104 // Check if the component's relationship is a BelongsToMany relationship.
102105 if ($ component ->getRelationship () instanceof BelongsToMany) {
103106 // Wrap the state in a collection and convert it to an array if it's not set.
104- $ state = Collection::wrap ($ state ?? []);
107+ $ state = Arr::wrap ($ state ?? []);
108+
109+ $ pivotData = $ component ->getPivotData ();
105110
106111 // Sync the relationship with the provided state (IDs).
107- $ component ->getRelationship ()->sync ($ state ->toArray ());
112+ if ($ pivotData === []) {
113+ $ component ->getRelationship ()->sync ($ state ?? []);
114+
115+ return ;
116+ }
117+
118+ // Sync the relationship with the provided state (IDs) plus pivot data.
119+ $ component ->getRelationship ()->syncWithPivotValues ($ state ?? [], $ pivotData );
108120 }
109121 });
110122
0 commit comments