I have the following form inputs in a laravel 10 application:
@foreach ($roles as $role)
<div class="checkbox">
<label>
{{-- Hidden field to ensure unchecked checkboxes are recognized --}}
<input type="hidden" name="user_roles[]" value="" id="hidden_{{ $role->name }}">
{{ html()->checkbox('user_roles[]')->value($role->id)->checked(in_array($role->id, old('user_roles[]', $user->roles->pluck('id')->toArray())))->id($role->name) }} {{ $role->label }}
</label>
</div>
@endforeach
There is a hidden checkbox to ensure unchecked checkboxes are posted for any form validation. When I post the form without checking any checkboxes,the hidden checkbox array will still get posted with a null value so it isn’t exactly empty
"user_roles" => array:1 [▼
0 => null
]
Ideally I would want to post the hidden field as an empty array so that in the form request it which obviously isn’t possible:
“user_roles” => array:1 []
Basically I want the form in edit mode on intial load to pre check any saved user roles. If the user then uncheck/checks different roles and on form submission error and I want to preserve those selections. currently if i uncheck all the checkboxes and post the form the validation rule is getting bypassed
$rules = [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,email,' . ($this->isUpdate ? $this->id : '' ),
'password' => [$this->isUpdate ? 'nullable' : 'required', 'confirmed', Password::min(8)->letters()->numbers()->uncompromised()],
'user_roles' => [
'required',
'array',
'min:1'
],
];
I’ve tried setting different values to the hidden field to no avail e.g. non of the following work – they all add an initial item to the array
<input type="hidden" name="user_roles[]" value="0" id="hidden_{{ $role->name }}">
<input type="hidden" name="user_roles[]" id="hidden_{{ $role->name }}">
This was all working fine in Laravel collective but struggling to get it to work with spatie html.