I am trying to attach arrays of data. I have collection of products and try to get individual items, and insert into pivot table. I don't want to put attach in loop because I want one db call
if($cart->packages)
{
foreach( $cart->packages as $k => $v)
{
$collection = Collection::find($k)->products;
// dd($collection);
$records_array[] = $k;
$name[]['name'] = $v['name'];
$quantity[]['quantity'] = $v['quantity'];
}
// dd($records_array);
$order->collections()->attach($records_array, $name, $quantity);
}
First of all you need to import DB facade some where after namespace and before class name:
use Illuminate\Support\Facades\DB;
The in your controller added following for testing:
$cart = array(
array('name' => 'some product 1', 'quantity' => '1'),
array('name' => 'some product 2', 'quantity' => '2'),
array('name' => 'some product 3', 'quantity' => '1'),
);
if ($cart)
{
DB::table('order')->insert($cart);
}
I have tested on my local environment and it works.
You can take look at Running An Insert Statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With