Am building an e-commerce app where I want to update two records in my database with some couple of input fields from my html/blade template.
I have a product with its sizes as an option of the product. So a shirt can have small as option 1, medium as option 2 and large as option 3. I have then created a productProductOptions table with product_id column and product_option_id column.
If the admin wants to update a product, I loop through the productProductOptions table and present the product's options to the product/edit page. So once the necessary options are changed then I can grab them back into the productProductOptions again.
The DB:
product_id | product_option_id
1 | 2
1 | 3
This is my html :
@foreach($productOptions as $thisProduct)
<div class="row">
<div class="col-md-3">
<div class="form-group {{ $errors->has('option_id') ? 'has-error': '' }}">
<label for="size">Sizes:</label>
<select class="form-control" id="size" class="form-control" name="option_id[]">
@if(isset($thisProduct))
@foreach($options as $option)
<option value="{{ $option->id }}"
@if($thisProduct->productOption->id == $option->id) selected="selected" @endif
>{{ $option->name }}</option>
@endforeach
@endif
<select/>
</div>
</div>
@endforeach
This is my controller:
$productProductOptions = ProductProductOption::where('product_id', $product->id)->get();
for ($i=0; $i < count($request->option_id); $i++) {
foreach ($productProductOptions as $productProductOption) {
$productProductOption->update(['product_option_id' => $request->option_id[$i]]);
}
}
But it picks up the last option form the form and update both records with it.
For example: The admin picks small = option 1 and medium = option 2, both records get updated with 2.