Select::make("audience_{$rule}") ->label($label) ->multiple() ->searchable() ->options($options) ->afterStateHydrated(fn (Select $component, ?Model $record) => $component->state($record ? Audiences::get($type, $record->getKey())[$rule] : [])) ->saveRelationshipsUsing(function (Model $record, Select $component) use ($type) { // Alle Felder zusammen speichern (einmal pro Formular reicht, aber schadet nicht). $state = $component->getContainer()->getRawState(); Audiences::sync($type, $record->getKey(), [ 'role' => $state['audience_role'] ?? [], 'department' => $state['audience_department'] ?? [], 'location' => $state['audience_location'] ?? [], 'exclude_role' => $state['audience_exclude_role'] ?? [], ]); }) ->dehydrated(false); $roles = fn () => Role::query()->orderBy('name')->pluck('name', 'id')->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all(); return Section::make('Sichtbarkeit') ->description($description) ->collapsible() ->schema([ $field('role', 'Rollen', $roles), $field('department', 'Abteilungen', fn () => self::distinct('department')), $field('location', 'Standorte', fn () => self::distinct('location')), $field('exclude_role', 'Ausgeschlossene Rollen', $roles) ->helperText('Personen mit einer dieser Rollen sehen es nie – auch wenn eine Angabe oben passt. Beispiel: Klientinnen und Klienten von einer internen Seite ausschließen.'), ]); } /** * @return array */ private static function distinct(string $column): array { return User::query()->whereNotNull($column)->distinct()->orderBy($column)->pluck($column, $column)->all(); } }