How to validate Select relation field?

Hi guys, I have 3 simple models: Organization, Store, Contact. Each Contact can be assign to Store only of his own Organization. I want to use Select field with multiple option, but I need to validate that the stores saved in belongs to organization of that contact.
Forms\Components\Select::make('organization_id')
->label(__('Organization'))
->relationship('organization', 'name')
->preload()
->searchable()
->required()
->exists('organizations', 'id');

Forms\Components\Select::make('stores')
->label(__('Stores'))
->relationship(
'stores',
'name',
function (Builder $query, Forms\Get $get): void {
$organization = Organization::find($get('organization_id'));

if ($organization) {
$query->where('organization_id', $organization->id);
}
}
)
->preload()
->multiple(),
Forms\Components\Select::make('organization_id')
->label(__('Organization'))
->relationship('organization', 'name')
->preload()
->searchable()
->required()
->exists('organizations', 'id');

Forms\Components\Select::make('stores')
->label(__('Stores'))
->relationship(
'stores',
'name',
function (Builder $query, Forms\Get $get): void {
$organization = Organization::find($get('organization_id'));

if ($organization) {
$query->where('organization_id', $organization->id);
}
}
)
->preload()
->multiple(),
This works just fine, but user can select Organization first, then select some Stores, then change organization and click save. It will save organization with stores that dont belongs to that organization.
5 Replies
Matthew
Matthewβ€’2mo ago
Add ->live to Forms\Components\Select::make('organization_id')
Trauma Zombie
Trauma ZombieOPβ€’2mo ago
Hey, thank you, but still not working.
Firebat
Firebatβ€’2mo ago
use ->AfterStateUpdated on the org to $set the other fields to null; and then on the fields that depend on that relation you modify the query like this modifyQueryUsing: fn (Builder $query , Get $get) => $query->where(['team_id' => $get('team_id') ]) and where you put ->AfterStateUpdate, put ->live()
Trauma Zombie
Trauma ZombieOPβ€’2mo ago
Thank you, this is what I was looking for. πŸ™‚
Matthew
Matthewβ€’2mo ago
hmmm...would have thought the ->relationship handled the re-build without an additional afterstate...nevermind though.
Want results from more Discord servers?
Add your server