3

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.

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your assistance. I how I am getting a syntax error at foreach($i= 0; syntax error, unexpected ';'.
Oh I'm sorry it's a for statement, not foreach, I've modified my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.