如何在 Laravel 5 中获取复选框数组的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43393059/
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 get values of checkbox array in Laravel 5?
提问by aikutto
I created checkboxes in form using javascript:
我使用javascript在表单中创建了复选框:
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
When I check 1st and 3rd checkbox and submit the form, Input::get("is_ok")
returns me:
当我选中第一个和第三个复选框并提交表单时,Input::get("is_ok")
返回给我:
['on', 'on']
Is there any way to get value as ['on', null, 'on']
or ['on', 'off', 'on']
?
有没有办法获得价值 as ['on', null, 'on']
or ['on', 'off', 'on']
?
Thanks in advance.
提前致谢。
回答by Vaibhavraj Roham
Hey assign some values to checkboxes like user_id, product_id etc
what ever in your application.
嘿user_id, product_id etc
,为您的应用程序中的复选框分配一些值。
E.g. View
例如视图
<input type="checkbox" name="is_ok[]" value="1" />
<input type="checkbox" name="is_ok[]" value="2" />
<input type="checkbox" name="is_ok[]" value="3" />
E.g. Controller
例如控制器
<?php
if(isset($_POST['is_ok'])){
if (is_array($_POST['is_ok'])) {
foreach($_POST['is_ok'] as $value){
echo $value;
}
} else {
$value = $_POST['is_ok'];
echo $value;
}
}
?>
You will get array of selected checkbox.
您将获得选定复选框的数组。
Hope it helps..
希望能帮助到你..
回答by apokryfos
I think I have a "good" solution to this (kind of).
我想我有一个“好的”解决方案(有点)。
<input type="checkbox" name="is_ok[0]" />
<input type="checkbox" name="is_ok[1]" />
<input type="checkbox" name="is_ok[2]" />
(Forced indices here)
(这里是强制索引)
In the request:
在请求中:
$array = \Request::get("is_ok") + array_fill(0,3,0);
ksort($array);
This will ensure that (a) The checkbox indices are maintained as expected. (b) the gaps are filled when the request is received.
这将确保 (a) 复选框索引按预期维护。(b) 在收到请求时填补空白。
It's sloppy but may work.
这很草率,但可能会奏效。
回答by Daniel Ortegón
My solution is this for laravel 5
我的解决方案是针对 laravel 5
$request->get('is_ok[]');
回答by lewis4u
IMHO this is the best practice:
恕我直言,这是最佳做法:
In your migration set that db table field to boolean and default 0
在您的迁移中将该 db 表字段设置为布尔值和默认值 0
$table->boolean->('is_ok')->default(0);
{!! Form::checkbox('is_ok[]', false, isset($model->checkbox) ? : 0) !!}
and if you are not using laravel collective for forms then you can use vanilla php
如果您不使用 laravel 集体表单,那么您可以使用 vanilla php
<input type="checkbox" name="is_ok[]" value="<?php isset($model->checkbox) ? : 0; ?>" />