如何处理 Laravel 中未选中的复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48800663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle unchecked checkboxes in Laravel?
提问by Allfarid Morales García
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.
我在 Laravel 中有一个带有多个复选框的编辑表单。当我选中这些框并更新记录时,它可以正常工作,但是如果我取消选中该框,它不会返回任何值,因此记录不会更新并且该值在数据库中保持为真。
How can I handle unchecked checkboxes in Laravel?
如何处理 Laravel 中未选中的复选框?
回答by Allfarid Morales García
Place a hidden textbox with a 0 value beforethe checkbox so a 0 value is sent into the POST array.
在复选框之前放置一个值为 0 的隐藏文本框,以便将 0 值发送到 POST 数组中。
{{Form::hidden('value',0)}}
{{Form::checkbox('value')}}
回答by Jomoos
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');
回答by wajih
Try this
尝试这个
<input type="hidden" name="param" value="0">
<input type="checkbox" name="param" value="1">
if checkbox is checked => server get "1"
如果选中复选框 => 服务器获取“1”
otherwise => server get "0"
否则 => 服务器获取“0”
回答by Mr.Web
The best way I can think of is using ternary and null coalesce PHP operators:
我能想到的最好方法是使用三元和空合并 PHP 运算符:
$request->checkbox ? 1 : 0 ?? 0;
This will return 1
if checked, 0
if not checked or not available.
1
如果选中,0
如果未选中或不可用,这将返回。
回答by shushu304
In HTML forms when you check checkbox it's arrived with the POST,
在 HTML 表单中,当您选中复选框时,它会随 POST 一起到达,
and you don't check it ... so it's not exists at all in the POST.
你不检查它......所以它在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