Skip to content

Commit

Permalink
Fix can't save the same model twice
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 committed Apr 23, 2024
1 parent ce67a8b commit 9f5cb6d
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/Traits/HasPermissions.php
Original file line number Diff line number Diff line change
Expand Up @@ -401,14 +401,16 @@ public function givePermissionTo(...$permissions)
$model->unsetRelation('permissions');
} else {
$class = \get_class($model);
$saved = false;

$class::saved(
function ($object) use ($permissions, $model, $teamPivot) {
if ($model->getKey() != $object->getKey()) {
function ($object) use ($permissions, $model, $teamPivot, &$saved) {
if ($saved || $model->getKey() != $object->getKey()) {
return;
}
$model->permissions()->attach($permissions, $teamPivot);
$model->unsetRelation('permissions');
$saved = true;
}
);
}
Expand Down
6 changes: 4 additions & 2 deletions src/Traits/HasRoles.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,16 @@ public function assignRole(...$roles)
$model->unsetRelation('roles');
} else {
$class = \get_class($model);
$saved = false;

$class::saved(
function ($object) use ($roles, $model, $teamPivot) {
if ($model->getKey() != $object->getKey()) {
function ($object) use ($roles, $model, $teamPivot, &$saved) {
if ($saved || $model->getKey() != $object->getKey()) {
return;
}
$model->roles()->attach($roles, $teamPivot);
$model->unsetRelation('roles');
$saved = true;
}
);
}
Expand Down
1 change: 1 addition & 0 deletions tests/HasPermissionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,7 @@ public function it_can_sync_permissions_to_a_model_that_is_not_persisted()
$user = new User(['email' => 'test@user.com']);
$user->syncPermissions('edit-articles');
$user->save();
$user->save(); // test save same model twice

$this->assertTrue($user->hasPermissionTo('edit-articles'));

Expand Down
1 change: 1 addition & 0 deletions tests/HasRolesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ public function it_will_sync_roles_to_a_model_that_is_not_persisted()
$user = new User(['email' => 'test@user.com']);
$user->syncRoles([$this->testUserRole]);
$user->save();
$user->save(); // test save same model twice

$this->assertTrue($user->hasRole($this->testUserRole));

Expand Down

0 comments on commit 9f5cb6d

Please sign in to comment.