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/
the column qty and service was inserted properly but the price does not, I dont know why?
order_service table:
Schema::create('order_service', function (Blueprint $table) { $table->foreignId('service_id'); $table->foreignId('order_id'); $table->float('price')->default(0); $table->integer('qty')->default(0); $table->primary(['service_id','order_id']);
OrderController:
$services = $request->input('services', []); $quantities = $request->input('qty', []); $price=$request->input('price', []); for ($service=0; $service < count($services); $service++) { if ($services[$service] != '') { $order->services()->attach($services[$service], ['qty' => $quantities[$service]], ['price' => $price[$service]]); }
with dd($request):
"services" => array:2 [▼ 0 => "3" 1 => "2" ] "qty" => array:2 [▼ 0 => "861" 1 => "748" ] "price" => array:2 [▼ 0 => "20" 1 => "40"
dd($price[$service])
"20"
Data base outbut
| order_id | service_id |price | qty| | -------- | -------------- |______|____| | 2074 | 2 |0.00 |748 | | 2074 | 3 |0.00 |861 |
Can any one help?
Advertisement
Answer
In your controller, you are misusing the attach()
method:
$order->services()->attach( $services[$service], ['qty' => $quantities[$service]], ['price' => $price[$service]] // something wrong with your arrays here, it only needs one in the second argument );
The attach()
method should be used like this:
$order->services()->attach( $services[$service], [ 'qty' => $quantities[$service], 'price' => $price[$service] ] );
The second parameter is an array with all additional pivot values.