Skip to content

Commit

Permalink
Fix detaching user models on teams feature spatie#2220
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 committed Oct 19, 2022
1 parent 1cb0a5c commit 3cbed36
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Traits/HasPermissions.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ public static function bootHasPermissions()
return;
}

$teams = PermissionRegistrar::$teams;
PermissionRegistrar::$teams = false;
$model->permissions()->detach();
PermissionRegistrar::$teams = $teams;
});
}

Expand Down
3 changes: 3 additions & 0 deletions src/Traits/HasRoles.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ public static function bootHasRoles()
return;
}

$teams = PermissionRegistrar::$teams;
PermissionRegistrar::$teams = false;
$model->roles()->detach();
PermissionRegistrar::$teams = $teams;
});
}

Expand Down
26 changes: 26 additions & 0 deletions tests/TeamHasRolesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,32 @@ class TeamHasRolesTest extends HasRolesTest
/** @var bool */
protected $hasTeams = true;

/** @test */
public function it_deletes_pivot_table_entries_when_deleting_models()
{
$user1 = User::create(['email' => '[email protected]']);
$user2 = User::create(['email' => '[email protected]']);

setPermissionsTeamId(1);
$user1->assignRole('testRole');
$user1->givePermissionTo('edit-articles');
$user2->assignRole('testRole');
$user2->givePermissionTo('edit-articles');
setPermissionsTeamId(2);
$user1->givePermissionTo('edit-news');

$this->assertDatabaseHas('model_has_permissions', [config('permission.column_names.model_morph_key') => $user1->id]);
$this->assertDatabaseHas('model_has_roles', [config('permission.column_names.model_morph_key') => $user1->id]);

$user1->delete();

setPermissionsTeamId(1);
$this->assertDatabaseMissing('model_has_permissions', [config('permission.column_names.model_morph_key') => $user1->id]);
$this->assertDatabaseMissing('model_has_roles', [config('permission.column_names.model_morph_key') => $user1->id]);
$this->assertDatabaseHas('model_has_permissions', [config('permission.column_names.model_morph_key') => $user2->id]);
$this->assertDatabaseHas('model_has_roles', [config('permission.column_names.model_morph_key') => $user2->id]);
}

/** @test */
public function it_can_assign_same_and_different_roles_on_same_user_different_teams()
{
Expand Down

0 comments on commit 3cbed36

Please sign in to comment.