Ezra Ezra - 3 months ago 15
PHP Question

laravel post unchecked checkbox with multipul checkboxes

I have a number of options within a form, that are saved in a loop after submission. Each of these options includes a check-box, each option has the same checkbox and I'm using the following technique to add the unchecked checkbox value to the POST data:

As I want to know if the checkbox was not checked and get that value.

{{ Form::hidden('exclude[]', 0) }}
{{ Form::checkbox('exclude[]', 1) }}


However, with this technique the result is that an extra value is added to the array of 'exclude' items.

'exclude' =>
array (size=10)
0 => string '0' (length=1)
1 => string '0' (length=1)
2 => string '0' (length=1)
3 => string '0' (length=1)
4 => string '1' (length=1)
5 => string '0' (length=1)
6 => string '0' (length=1)
7 => string '0' (length=1)
8 => string '0' (length=1)
9 => string '0' (length=1)


In the code this result is taken from there are only 9 instances of the technique above, but once a checkbox is ticked, the value is added to the array rather than replacing it. If I checked the checkbox for every option it would return 18 items in the 'exclude' array.

How can I make it work correctly, as in if its checked, not return the unchecked value as well as the checked. Hope that makes sense :P

Heres an example of whats happening: http://web-4bdd8023-5cb2-4f23-adfa-b08b0b136149.runnable.com/

Answer

You could try to adjust the field names to include an index.

// some loop
{{ Form::hidden("exclude[$i]", 0) }}
{{ Form::checkbox("exclude[$i]", 1) }}