@@ -273,6 +273,50 @@ public function render(): View
273273 }
274274}
275275
276+ class ModalTableSelectWithEagerLoadedBelongsToManyRelationship extends Component implements HasActions, HasSchemas
277+ {
278+ use InteractsWithActions;
279+ use InteractsWithSchemas;
280+
281+ public $ data = [];
282+
283+ public User $ record ;
284+
285+ public function mount (): void
286+ {
287+ $ this ->record ->load ('teams ' );
288+ $ this ->form ->fill ([]);
289+ }
290+
291+ public function hydrate (): void
292+ {
293+ $ this ->record ->load ('teams ' );
294+ }
295+
296+ public function form (Schema $ form ): Schema
297+ {
298+ return $ form
299+ ->schema ([
300+ ModalTableSelect::make ('teams ' )
301+ ->relationship ('teams ' , 'name ' )
302+ ->tableConfiguration (TeamsTable::class)
303+ ->multiple (),
304+ ])
305+ ->model ($ this ->record )
306+ ->statePath ('data ' );
307+ }
308+
309+ public function save (): void
310+ {
311+ $ this ->form ->getState ();
312+ }
313+
314+ public function render (): View
315+ {
316+ return view ('livewire.form ' );
317+ }
318+ }
319+
276320class ModalTableSelectWithBelongsToManyRelationshipAndModifyQuery extends Component implements HasActions, HasSchemas
277321{
278322 use InteractsWithActions;
@@ -814,6 +858,23 @@ public function render(): View
814858 expect ($ pivotRows ->first ()->role )->toBe ('viewer ' );
815859 expect ($ pivotRows ->last ()->role )->toBe ('viewer ' );
816860 });
861+
862+ it ('invalidates the cached `BelongsToMany` relationship after save so a subsequent reload does not re-attach detached rows ' , function (): void {
863+ $ user = User::factory ()->create ();
864+ $ teams = Team::factory ()->count (2 )->create ();
865+ $ user ->teams ()->attach ($ teams );
866+
867+ $ component = livewire (ModalTableSelectWithEagerLoadedBelongsToManyRelationship::class, ['record ' => $ user ])
868+ ->fillForm (['teams ' => []])
869+ ->call ('save ' );
870+
871+ expect ($ user ->fresh ()->teams )->toHaveCount (0 )
872+ ->and ($ component ->instance ()->data ['teams ' ])->toBe ([]);
873+
874+ $ component ->call ('save ' );
875+
876+ expect ($ user ->fresh ()->teams )->toHaveCount (0 );
877+ });
817878});
818879
819880describe ('saving BelongsTo relationships ' , function (): void {
0 commit comments