Tricks

Hide and show form field bases on a multi-select or checkbox list

Jul 6, 2022
Suhendra Katrali
Form builder

Let's say your user has many roles. On user form you want to show a field only for certain roles (in below example the role IDs are 2 and 3). And make it empty for other roles.

Forms\Components\MultiSelect::make('roles') // or
Forms\Components\CheckboxList::make('roles')
->relationship('roles', 'name')
->reactive()
->afterStateUpdated(function (Closure $set, Closure $get) {
if((! in_array(3, $get('roles'))) && (! in_array(2, $get('roles')))){ ) // 3 and 2 are roles IDs
$set('hospital_id', null);
}
}),
Forms\Components\Select::make('hospital_id')
->label('Hospital')
->relationship('hospital', 'name')
->hidden(fn (Closure $get): bool => ! (in_array(3, $get('roles')) || in_array(2, $get('roles')))) // 3 and 2 are role IDs
->searchable(),

No comments yet…