Laravel - 在数据库中存储多个复选框表单值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52447032/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:04:45  来源:igfitidea点击:

Laravel - Store multiple checkbox form values in database

javascriptphphtmllaravellaravel-5

提问by Grosu Dumitru

So I've got this code

所以我有这个代码

View:

看法:

<div id="checkboxes">
                         <input type="checkbox" class="checkbox" name="services" value="{{ $service->id }}" id="{{ $service->id }}" />
                         <label class="whatever" for="{{ $service->id }}"><p class="serv-text"> {{ $service->service_name }} + ${{ $service->price }} </p></label>
                             </div>

Controller:

控制器:

  public function store(Request $request)
    {
       orders::create(Request::all());
        return 'test';
    }

Model:

模型:

class orders extends Model
{
    protected $fillable = [
    'category', 
    'services',
    'total_price',
    'user_id',
    'status',
    'user_id'];
}

When I try to submit the form, in the database at services there is only one number even if I checked multiple boxes when I submitted the form. I've tried to find on google a solution but nothing.

当我尝试提交表单时,即使我在提交表单时选中了多个框,在 services 的数据库中也只有一个数字。我试图在谷歌上找到一个解决方案,但一无所获。

回答by Luká? Irsák

If you have multiple checkboxes like this:

如果您有多个这样的复选框:

<input type="checkbox" name="services" value="1"/>
<input type="checkbox" name="services" value="2"/>
<input type="checkbox" name="services" value="3"/>

It will send's only one value to server, cause name must be unique. Workaround is to use array inputs:

它只会向服务器发送一个值,因为名称必须是唯一的。解决方法是使用数组输入:

<input type="checkbox" name="services[]" value="1"/>
<input type="checkbox" name="services[]" value="2"/>
<input type="checkbox" name="services[]" value="3"/>

Then you can grab that input in controller and do something like this:

然后您可以在控制器中获取该输入并执行以下操作:

$services = $request->input('services');
foreach($services as $service){
 orders::create($service);
}

Validation of arrays in Laravel:

Laravel 中数组的验证:

https://laravel.com/docs/5.7/validation#validating-arrays

https://laravel.com/docs/5.7/validation#validating-arrays

More about input arrays:

有关输入数组的更多信息:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Handling_multiple_checkboxes

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Handling_multiple_checkboxes

How to get form input array into PHP array

如何将表单输入数组转换为 PHP 数组