Laravel-在数据库中存储多个复选框表单值 [英] Laravel - Store multiple checkbox form values in database

查看:150
本文介绍了Laravel-在数据库中存储多个复选框表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码

查看:

<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>

控制器:

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

型号:

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

当我尝试提交表单时,即使在提交表单时选中了多个复选框,在服务数据库中也只有一个数字. 我试图在Google上找到解决方案,但没找到.

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.

推荐答案

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

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);
}

Laravel中的数组验证:

Validation of arrays in Laravel:

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

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

More about input arrays:

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

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

这篇关于Laravel-在数据库中存储多个复选框表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆