I am trying to insert data to a pivot table order_serrvice
using arrays. I follow this code: https://blog.quickadminpanel.com/master-detail-form-in-laravel-jquery-create-order-with-products/
OrderController:
$order = Order::create($data);
$services = $request->input('services', []);
$quantities = $request->input('quantities', []);
for ($service = 0; $service < count($services); $service ) {
if ($services[$service] != '') {
$order->services()->attach($services[$service], ['quantity' => $quantities[$service]]);
}
}
The blade page:
<tbody>
<tr id='addr0'>
<td>1</td>
<td>
<select name="services[]" class="form-control">
<option value="">-- choose service --</option>
@foreach ($services as $service)
<option value="{{ $service->id }}">
{{ $service->name }} (${{ number_format($service->price, 2) }})
</option>
@endforeach
</select>
{{--<input type="text" name='service[]' placeholder='Enter Product Name' class="form-control"/>--}}
</td>
<td><input type="number" name='qty[]' placeholder='Enter Qty' class="form-control qty" step="0" min="0"/></td>
<td><input type="number" name='price[]' placeholder='Enter Unit Price' class="form-control price" step="0.00" min="0"/></td>
<td><input type="number" name='total[]' placeholder='0.00' class="form-control total" readonly/></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
With dd($request)
:
"services" => array:2 [▼
0 => "1"
1 => "2"
]
"qty" => array:2 [▼
0 => "27"
1 => "2"
]
"price" => array:2 [▼
0 => "489"
1 => "4"
]
"total" => "23647.69"
"sub_total" => "13211.00"
"vat" => "10436.69"
dd($services[$service])
:
"1"
Error:
ErrorException Undefined offset: 0 $order->services()->attach($services[$service], ['quantity' => $quantities[$service]]);
Can any one help?
CodePudding user response:
instead of checking null check with isset. your for loop starts with 0 so initially it checking the zeroth value and there your array doesn't have that index. so change iteration value of loop starts
for ($service=1; $service <= count($services); $service ) {
if (isset($services[$service])) {
$order->services()->attach($services[$service], ['quantity' => $quantities[$service]]);
}
}
CodePudding user response:
I fixed the essue it is simple mistake I just replace the Quantity with qty in OrderController
$order = Order::create($data);
$services = $request->input('services', []);
$quantities = $request->input('qty', []);
for ($service = 0; $service < count($services); $service ) {
if ($services[$service] != '') {
$order->services()->attach($services[$service], ['qty' => $quantities[$service]]);
}
}