label($label) ->multiple() ->preload() ->options(fn () => Role::query()->where('slug', '!=', Role::ADMINISTRATION)->orderBy('name')->pluck('name', 'id')->all()) ->afterStateHydrated(fn (Select $component, ?Model $record) => $component->state($record ? Grant::query()->where('ability', $ability)->where('resource_type', $resourceType)->where('resource_id', $record->getKey())->pluck('role_id')->all() : [])) ->saveRelationshipsUsing(function (Model $record, ?array $state) use ($ability, $resourceType, $includeChildren) { $roleIds = array_map('intval', $state ?? []); $existing = Grant::query()->where('ability', $ability)->where('resource_type', $resourceType)->where('resource_id', $record->getKey()); (clone $existing)->whereNotIn('role_id', $roleIds)->get()->each->delete(); foreach (array_diff($roleIds, (clone $existing)->pluck('role_id')->all()) as $roleId) { Grant::query()->create(['role_id' => $roleId, 'ability' => $ability, 'resource_type' => $resourceType, 'resource_id' => $record->getKey(), 'include_children' => $includeChildren]); } }) ->dehydrated(false); } }