【问题标题】:Dynamically add form input fields and store values with Laravel 5使用 Laravel 5 动态添加表单输入字段并存储值
【发布时间】:2018-01-14 16:39:17
【问题描述】:

我正在使用产品和价格模型。我的 products 表有一个 id 和 name 列,而我的 prices 表有一个 id、product_id、cost 和 date 列。 price 表上的 product_id 引用 products 表上的 id。我的表单为每个产品显示一个字段,以便用户不时输入价格。我的挑战是如何处理请求数据,以便价格与 product_id 相对应。下面是我目前写的代码

表格

<form class="form-horizontal" method="POST" action="{{ url('/home/prices') }}">
{{ csrf_field() }}
@if(isset($products) && !empty($products))
    @foreach($products as $product)
        <div class="form-group">
            <div>
                <input type="hidden" class="form-control" name="product_id[]" value="{{ $product->id }}">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2" for="{{ $product->name }}">{{ ucwords($product->name) }}</label>

            <div class="col-sm-3">
                <input type="text" class="form-control" name="cost[]">
            </div>
        </div>
    @endforeach
@else
    Sorry, no product available currently.
@endif

<button type="submit" class="btn btn-default">Add</button>
</form>

价格控制器

public function store(Request $request)
{
//dd($request);
foreach ($request->input('cost') as $cost) {
    Price::create([
        'product_id' => $request->product_id,
        'date' => Carbon::now(),
        'cost' => $cost,
        'trend' => 0
    ]);
}

return redirect('/home');
}

这是我在转储请求数据时得到的

当然我的代码会抛出这个错误 at Builder-&gt;insertGetId(array('product_id' =&gt; array('1', '2', '3'), 'date' =&gt; object(Carbon), 'cost' =&gt; '14.05', 'trend' =&gt; 0, 'updated_at' =&gt; '2017-08-07 11:21:47', 'created_at' =&gt; '2017-08-07 11:21:47'), 'id')

我该如何解决这个问题?

【问题讨论】:

    标签: php mysql html laravel laravel-5.4


    【解决方案1】:

    您可以在输入数组中使用索引或键/值对的概念,如下所示:

    试试这个,

    foreach ($request->input('cost') as $key=>$cost) {
        Price::create([
            'product_id' => $request->product_id[$key],
            'date' => Carbon::now(),
            'cost' => $cost,
            'trend' => 0
        ]);
    }
    

    这将保存您的数据,例如

    1 -> 14.05
    2 -> 13.75
    3 -> 12.99
    

    希望你能理解。

    【讨论】:

      【解决方案2】:
      foreach ($request->input('cost') as $key=>$cost) {
      
          Price::create([
              'product_id' => $request->product_id[$key],
              'date' => Carbon::now(),
              'cost' => $cost,
              'trend' => 0
          ]);
      }
      

      正如您所看到的,整个数组都在产品的 id 中传递,因此您需要提及需要插入的特定 id

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-27
        • 1970-01-01
        • 1970-01-01
        • 2016-07-30
        • 2016-07-19
        • 2016-08-26
        • 1970-01-01
        • 2018-11-01
        相关资源
        最近更新 更多