-
I'm using this package with teams enabled. There are few niggles but that is for another time! My biggest issue at the moment is with cascade on delete. There doesn't really appear to be much, if a role is removed then any related permissions and pivots will be removed but if a team or user is removed then the related records hang around in the package tables? Is there something I can alter in the migrations to get cascade on delete to work as expected or do I need to hook into Eloquent events? Edit: Ok so as it is a polymorphic relationship I understand a DB level cascade via foreign keys won't work, is there any example code I can use in Eloquent events to achieve the same results? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
With laravel-permission/src/Traits/HasPermissions.php Lines 22 to 31 in 10d4c14 But maybe needs work for that |
Beta Was this translation helpful? Give feedback.
-
I did a PR, please test it #1935 namespace Spatie\Permission\Traits;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Permission\PermissionRegistrar;
trait TeamHasRoles
{
public static function bootTeamHasRoles()
{
static::deleting(function ($model) {
$modelHasSoftDeleting = method_exists($model, 'isForceDeleting');
$roleHasSoftDeleting = method_exists(app(PermissionRegistrar::class)->getRoleClass(), 'isForceDeleting');
if ($modelHasSoftDeleting && ! $model->isForceDeleting()) {
if ($roleHasSoftDeleting) {
$model->specific_roles()->delete();
}
return;
}
$model->roles()->detach();
$model->permissions()->detach();
$roleDelete = $roleHasSoftDeleting && $modelHasSoftDeleting && $model->isForceDeleting() ? 'forceDelete' : 'delete';
$model->specific_roles()->$roleDelete();
});
}
/**
* A team may have multiple roles on multiple models.
*/
public function roles(): BelongsToMany
{
return $this->belongsToMany(
app(PermissionRegistrar::class)->getRoleClass(),
config('permission.table_names.model_has_roles'),
PermissionRegistrar::$teamsKey,
PermissionRegistrar::$pivotRole
);
}
/**
* A team may have multiple especific roles.
*/
public function specific_roles(): HasMany
{
return $this->hasMany(
app(PermissionRegistrar::class)->getRoleClass(),
PermissionRegistrar::$teamsKey
);
}
/**
* A team may have multiple direct permissions on multiple models.
*/
public function permissions(): BelongsToMany
{
return $this->belongsToMany(
app(PermissionRegistrar::class)->getPermissionClass(),
config('permission.table_names.model_has_permissions'),
PermissionRegistrar::$teamsKey,
PermissionRegistrar::$pivotPermission
);
}
} |
Beta Was this translation helpful? Give feedback.
-
So this trait would need to be on my Team model? |
Beta Was this translation helpful? Give feedback.
I did a PR, please test it #1935