Select::make('relation_id') ->label(__('Relation')) ->relationship('relation', 'name') ->live() ->searchable() ->preload() ->required() ->afterStateUpdated(function (callable $set) { $set('parent_project_id', null); $set('contact_id', null); }), Select::make('parent_project_id') ->label(__('Parent project')) ->relationship( name: 'parentProject', titleAttribute: 'name', modifyQueryUsing: fn (Builder $query, Get $get) => $query // Only projects with the same relation (with null check) ->where('relation_id', $get('relation_id')) // Apply exclusions only when editing ->when($get('id'), function (Builder $query, $id) { return $query // Exclude the current project ->where('id', '!=', $id) // Exclude all child projects (projects that have this project as their parent) ->whereNotIn('id', function ($subQuery) use ($id) { $subQuery->select('id') ->from('projects') ->where('parent_project_id', $id); }); }) ) ->getOptionLabelFromRecordUsing(fn ($record) => $record->number_with_name) ->searchable() ->preload() ->live(), Select::make('contact_id') ->label(__('Contact')) ->relationship( name: 'contact', titleAttribute: 'name', modifyQueryUsing: fn (Builder $query, Get $get) => $query->whereHas( 'relations', fn (Builder $query) => $query->where('id', '=', $get('relation_id')) ) ) ->live() ->getOptionLabelFromRecordUsing(fn ($record) => $record->name) ->preload() ->searchable() ->required(), TextInput::make('number') ->label(__('Project number')) ->unique() ->integer() ->mask('999999999') ->minLength(1) ->maxLength(9) ->belowContent(fn () => __('Latest project number: :number', [ 'number' => Project::latestProjectNumber(), ])) ->required(), TextInput::make('name') ->label(__('Project name')) ->required() ->partiallyRenderAfterStateUpdated() ->suffix(function (Get $get) { if (! $get('auto_fill_name_suffix')) { return null; } $relationName = null; $contactName = null; if ($relationId = $get('relation_id')) { $relation = Relation::find($relationId); $relationName = $relation?->name; } if ($contactId = $get('contact_id')) { $contact = Contact::find($contactId); $contactName = $contact?->name; } return Str::of(' ') ->when($relationName, fn ($str) => $str->append("{$relationName}")) ->when($contactName, fn ($str) => $str->append(" {$contactName}")); }, isInline: true) ->belowContent([ Checkbox::make('auto_fill_name_suffix') ->label(__('Auto-fill name suffix')) ->helperText(__('Automatically append the relation and contact name to the project name.')) ->dehydrated(false) ->reactive() ->afterStateUpdated(fn (Set $set) => $set('name', null)), ]),