File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -443,8 +443,17 @@ public function syncPermissions(...$permissions): static
443443 {
444444 if ($ this ->getModel ()->exists ) {
445445 $ this ->collectPermissions ($ permissions );
446- $ this ->permissions ()->detach ();
447- $ this ->setRelation ('permissions ' , collect ());
446+
447+ if (Config::eventsEnabled ()) {
448+ $ currentPermissions = $ this ->permissions ()->get ();
449+
450+ if ($ currentPermissions ->isNotEmpty ()) {
451+ $ this ->revokePermissionTo ($ currentPermissions );
452+ }
453+ } else {
454+ $ this ->permissions ()->detach ();
455+ $ this ->setRelation ('permissions ' , collect ());
456+ }
448457 }
449458
450459 return $ this ->givePermissionTo ($ permissions );
Original file line number Diff line number Diff line change 675675 });
676676});
677677
678+ it ('fires detach event when syncing permissions ' , function () {
679+ Event::fake ([PermissionDetachedEvent::class, PermissionAttachedEvent::class]);
680+ app ('config ' )->set ('permission.events_enabled ' , true );
681+
682+ $ this ->testUser ->givePermissionTo ('edit-articles ' , 'edit-news ' );
683+
684+ $ this ->testUser ->syncPermissions ('edit-articles ' );
685+
686+ expect ($ this ->testUser ->hasPermissionTo ('edit-articles ' ))->toBeTrue ();
687+ expect ($ this ->testUser ->hasPermissionTo ('edit-news ' ))->toBeFalse ();
688+
689+ Event::assertDispatched (PermissionDetachedEvent::class, function ($ event ) {
690+ $ names = collect ($ event ->permissionsOrIds )->map (
691+ fn ($ permission ) => is_object ($ permission )
692+ ? $ permission ->name
693+ : app (Permission::class)::findById ($ permission )->name
694+ );
695+
696+ return $ event ->model instanceof User
697+ && ! $ event ->model ->hasPermissionTo ('edit-news ' )
698+ && $ names ->contains ('edit-news ' );
699+ });
700+
701+ Event::assertDispatched (PermissionAttachedEvent::class, function ($ event ) {
702+ return $ event ->model instanceof User
703+ && $ event ->model ->hasPermissionTo ('edit-articles ' );
704+ });
705+ });
706+
678707it ('can be given a permission on role when lazy loading is restricted ' , function () {
679708 expect (Model::preventsLazyLoading ())->toBeTrue ();
680709
You can’t perform that action at this time.
0 commit comments