I'm working with a Product & Price model. My products table has an id and name column, while my prices table has an id,product_id,cost and date column. The product_id on the prices table references the id on the products table. My form displays a field for each product so that the user will then enter the price from time to time. My challenge is how to handle the request data so that the price will correspond to the product_id. Below is the code i have written so far
Form
<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>
PriceController
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');
}
This what i get when i dump the request data
Of course my code throws up this error
at Builder->insertGetId(array('product_id' => array('1', '2', '3'), 'date' => object(Carbon), 'cost' => '14.05', 'trend' => 0, 'updated_at' => '2017-08-07 11:21:47', 'created_at' => '2017-08-07 11:21:47'), 'id')
How do i fix this?