I have a form with multiple checkbox
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="checkbox" name="group_checkbox[]" value="1" />
So when i click the submit button in to submit the form it only sends the checked boxes.
I searched on the net and found that we can include hidden field above the real checkbox like so:
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
<input type="hidden" name="group_checkbox[]" value="0" />
<input type="checkbox" name="group_checkbox[]" value="1" />
But when i do var_dump($request->group_checkbox)
in Laravel Controller
it shows
array(10) { [0]=> string(1) "0" [1]=> string(1) "1" [2]=> string(1) "0" [3]=> string(1) "1" [4]=> string(1) "0" [5]=> string(1) "1" [6]=> string(1) "0" [7]=> string(1) "1" [8]=> string(1) "0" [9]=> string(1) "1" }
when all 5 checkboxes are checked.
and shows
array(5) { [0]=> string(1) "0" [1]=> string(1) "0" [2]=> string(1) "0" [3]=> string(1) "0" [4]=> string(1) "0" }
when no checkboxes are checked.
So why is it sending (0 and 1) when a checkbox is checked and not just 1 instead
This is how PHP handles multiple values for parameters ending in []. If you want to overwrite the 0 value with a checked checkbox, you will need to explicitly name the index, otherwise PHP interprets it as values that should be appended to the array.
So, use either
grouped_checkbox
orgrouped_checkbox[0]
.Like this: