'How to handle unchecked checkboxes in Laravel?

I have an edit form with several checkboxes in Laravel. When I check the boxes and update the record, it works correctly, but if I uncheck the box it doesn't return any value so the record doesn't update and the value remains true in the database.

How can I handle unchecked checkboxes in Laravel?



Solution 1:[1]

From mozilla documentation on checkbox:

If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all.

So, the following will do the trick:

$isChecked = $request->has('checkbox-name');

Solution 2:[2]

Place a hidden textbox with a 0 value before the checkbox so a 0 value is sent into the POST array.

{{Form::hidden('value',0)}}
{{Form::checkbox('value')}}

Solution 3:[3]

Try this

<input type="hidden" name="param" value="0">
<input type="checkbox" name="param" value="1">

if checkbox is checked => server get "1"

otherwise => server get "0"

Solution 4:[4]

The best way I can think of is using ternary and null coalesce PHP operators:

$request->checkbox ? 1 : 0 ?? 0;

This will return 1 if checked, 0 if not checked or not available.

Solution 5:[5]

In HTML forms when you check checkbox it's arrived with the POST,

and you don't check it ... so it's not exists at all in the POST.

so you need to check if it's exists ...

if($request->has('input-name')) {
     $value = $request->input('input-name')
}
else {
     $value = "put default value (false)";
}
.... 
do your stuff with the value

Solution 6:[6]

simply do

$somestate = 0;

if (isset($request -> checkox)) {
    $somestate = 1;

}

Solution 7:[7]

maybe you can just check if the input checkbox exists, if it is exists, $value equals input checkbox value, and if it doesnt exists that means checkbox is unchecked, so $value is false. You also have to add a form request to be sure that the input contains a boolean

$value = $request->has('checkbox') ? $request->input('checkbox') : false

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jomoos
Solution 2 Allfarid Morales García
Solution 3 Wajih
Solution 4 Mr.Web
Solution 5 shushu304
Solution 6
Solution 7