简体   繁体   English

Laravel表格:允许用户一次添加多个产品

[英]Laravel Form: Allow user to add multiple products at a time

I have a form where the user has to select a product from dropdown and enter the qty used. 我有一个表格,用户必须从下拉菜单中选择一种产品并输入使用的数量。 I want the user to be able to add multiple products at a time. 我希望用户能够一次添加多个产品。 I need help in processing this data. 我需要帮助来处理这些数据。

This is how I have done it so far. 到目前为止,这就是我所做的。 I have kept 6 pairs of fields and the user has to fill in the first but others are optional, here is the blade code. 我保留了6对字段,用户必须填写第一对,但其他字段是可选的,这是刀片代码。

{!! Form::open(['route' => 'parts.raw.store', 'id' => 'raw-part-form' , 'class'=>'raw-part-form','name'=>'raw-part-form' ]) !!}
@for($in=0;$in<6;$in++)
    <div class='col-md-7'>
        <label for="raw_material_id"{{$in}}>Packing Material</label>
        {!!  Form::select('raw_material_id'.$in, $raw_materials
              ->lists('display_name','id')->prepend('',''),null,
              ['class' => 'form-control', 'id' => 'raw_material_id'.$in])!!}
     </div>
     <div class='col-md-5'>
          <label for="qty_used{{$in}}">Qty used</label>
          <input type="number" min="1" step="1" class="form-control"
          id="qty_used{{$in}}" name="qty_used{{$in}}" placeholder="Qty Used"">
     </div>
@endfor

在此处输入图片说明

I am not sure if this is a good approach. 我不确定这是否是一个好方法。 I am also confused how to process it in the controller. 我也很困惑如何在控制器中处理它。

Something like: 就像是:

For blade: 对于刀片:

            @foreach ($foods as $k => $food) // or 1 to 6
            <tr>
              <td>
                <input type="number" name="item[{{$k}}][qty]" value="0">
                <input type="hidden" name="item[{{$k}}][id]" value="{{$food->id}}">
              </td>
              <td>{{ $food->name }}</td>
              <td>{{ $food->price }} €</td>

              <td>
                <a href="/cart/add/{{$food->id}}">+</a>
              </td>
            </tr>
            @endforeach

Controller: 控制器:

public function checkout(Request $request)
{
  $input = $request->all();

  foreach ($input['item'] as $item) {
    $this->ValidQtyCheck($item['qty']); // >0 or remove it
    $food = Food::findOrFail($item['id'])->toArray();
    Cart::add($item['id'], $food['name'], $item['qty'], $food['price']);
  }

  return redirect('/cart/view');
}

And pro tip, for dinamic adding instead of 6 always: pro tip 专业提示,用于动态添加而不是始终添加6: 专业提示


Validating Arrays 验证数组

Validating array form input fields doesn't have to be a pain. 验证数组表单输入字段不必费劲。 For example, to validate that each e-mail in a given array input field is unique, you may do the following: 例如,要验证给定数组输入字段中的每个电子邮件都是唯一的,您可以执行以下操作:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Validating Arrays 验证数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM