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
->relationship('roles', 'name')
->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);
->relationship('hospital', 'name')
->hidden(fn (Closure $get): bool => ! (in_array(3, $get('roles')) || in_array(2, $get('roles')))) // 3 and 2 are role IDs

No comments yet…