Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel attach arrays of data to pivot

Tags:

php

laravel

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);
    }
like image 679
Vladimir Stus Avatar asked Jan 16 '26 22:01

Vladimir Stus


1 Answers

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

like image 148
Maytham Avatar answered Jan 19 '26 11:01

Maytham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!