【发布时间】:2017-04-26 20:54:40
【问题描述】:
我正在尝试在电子商务网站中建立一个员工区域,允许员工查看可用产品表,编辑他们的详细信息并通过单击按钮进行更新。
目前我在使用实际更新功能时遇到了问题,因为我的请求输入一直返回 null,这意味着查询生成器失败。我似乎也想不出一个好方法来唯一标识表中的每个输入,这可能是主要问题。
编辑问题已解决。表单标签必须包裹每一行,感谢所有就输入数组提供建议的人。代码如下:
<div class="container">
<div class="jumbotron text-center clearfix">
@foreach($products as $index => $product)
@if ($index == 0)
<h2>{{$product->category}} Products </h2>
@endif
@endforeach
</div>
<table id="orders" class="table table-striped table-inverse">
<thead>
<tr id='tableHeader'>
<td>ID</td>
<td>Product Name</td>
<td>Slug</td>
<td>Quantity</td>
<td>Cost (£)</td>
</tr>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
<form action="{{ url('staff/storeUpdateProduct', [$product->id]) }}" method="POST" class="side-by-side">
{!! csrf_field() !!}
<td><input id="{{ $product->id}}" type="text" class="form-control" name="id[{{ $product->id}}]" value="{{ $product->id }}" readonly></td>
<td><input id="product_name[{{ $product->id}}]" type="text" class="form-control" name="product_name[{{ $product->id}}]" value="{{ $product->product_name }}"></td>
<td><input id="slug[{{ $product->id}}]" type="text" class="form-control" name="slug[{{ $product->id}}]" value="{{ $product->slug }}"></td>
<td><input id="quantity[{{ $product->id}}]" type="text" class="form-control" name="quantity[{{ $product->id}}]" value="{{ $product->quantity}}"></td>
<td><input id="cost[{{ $product->id}}]" type="text" class="form-control" name="cost[{{ $product->id}}]" value="{{ $product->cost }}"></td>
<td>
<input type="submit" class="btn btn-sm" value="Update">
</td>
</form>
</tr>
@endforeach
</tbody>
以及新的控制器代码:
/**
* Updates product details.
*
* @param Request $request
* @param String $id
* @return \Illuminate\Http\Response
*/
public function storeUpdateProduct(Request $request, $id)
{
$product = Product::where('id', '=', $id)->firstOrFail();
/*dd([
$request->product_name[$id],
$request->slug[$id],
$request->quantity[$id],
$request->cost[$id]
]);*/
$product->product_name = $request->product_name[$id];
$product->slug = $request->slug[$id];
$product->quantity = $request->quantity[$id];
$product->cost = $request->cost[$id];
$product->save();
return redirect()->route('staff.updateProducts');
}
【问题讨论】:
-
不确定这是否允许 $request->product_name_.$id,使用 sprintf('%s_%s', $request->product_name, $id) 连接它。
-
是的,我很确定这是不允许的,但这是我最后一次尝试我还没有尝试过的东西
-
您可以将输入名称指定为
array,将product_id指定为key -
点赞:
name="cost[{{$product->id}}]" -
很好,我会试试看是否有帮助