Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a multidimensional array in a database using laravel

Tags:

laravel

I am working on a eCommerce app in laravel. I want to save shopping cart values order and order details tables when the customer clicks checkout button. One order has many order details. I can insert order values: customerid, orderdate,shipdate,orderamount…… But as I have mentioned, one order have many orderdetails. This is my order details table:

**Id 
ordereid
product_id
price
quantity
price
amount**

Each order have many products as so:

Array ( [productids] => Array ( [0] => 6 [1] => 11 [2] => 7 [3] => 1 ) [quantity] => Array ( [0] => 2[1]=>1[2]=>3) [price] => Array ( [0] => 750.00 [1] => 456.00 [2] => 200.00 [3] => 700.00 ) [amount] => Array ( [0] => 1500 [1] => 456 [2] => 600 [3] => 1400 ) )

This is what I have done and am getting Array to string conversion exception

        for($i=0; $i < count($product); $i++)
        {
 $order_details =new Order_detail;  
    $order_details->order_id = $orders->id;        
    $order_details->product_id=$product['product_id'][$i];        
    $order_details->quantity=$product['quantity'][$i];    
    $order_details->unit_price=$product['price'][$i];        
    $order_details->amount=$product[amount][$i];

    $order_details->save();

       }

I have also tried to wrap each sub-array in foreach loop but only a single raw is inserted in the order details For example if the customer order shopping cart has three products, three rows should be inserted into the order details with:

    Id  
    ordered
    productid
    quantity
    price    
   amount

Any help.

like image 778
wafutech Avatar asked Jul 06 '26 13:07

wafutech


1 Answers

Here's what I'd do in this situation.

Step 1: grab the objects from the array

$order_details = [];
for($i= 0; $i < count($product); $i++){
    $order_details[] = [
        'order_id' => $orders->id,
        'product_id' => $product['product_id'][$i],
        'quantity' => $product['quantity'][$i],
        'unit_price' => $product['price'][$i],
        'amount' => $product['amount'][$i],
    ];
}

Step 2: Insert into table

\DB::table('order_details')->insert($order_details);

That's all you would need, more on the insert method can be found here

like image 122
Islam Al-Rayan Avatar answered Jul 08 '26 03:07

Islam Al-Rayan



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!