1

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 Controllerit 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

1 Answer 1

1

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 or grouped_checkbox[0].

Like this:

<input name="grouped_checkbox[0]" type="hidden" value="0">
<input name="grouped_checkbox[0]" type="checkbox" value="1"> <!-- this will overwrite the previous one, if checked -->

<input name="grouped_checkbox[1]" type="hidden" value="0">
<input name="grouped_checkbox[1]" type="checkbox" value="1"> <!-- this will overwrite the previous one, if checked -->

<!-- ... and so forth -->
Sign up to request clarification or add additional context in comments.

1 Comment

so you mean i should do this:<input type="hidden" name="group_checkbox[]" value="0" /> <input type="checkbox" name="group_checkbox[]" value="1" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.