Home > Software engineering >  take out components from array session and save in Database LARAVEL 9
take out components from array session and save in Database LARAVEL 9

Time:08-29

How are you? Hope well. I have e-commerce project on laravel 9. Actually i want to make checkout. I have add to cart function with sessions(it works fine), i want to make checkout. I am recieving cart with sessions

 $order = session('cart');
 var_dump($order);

This is working fine. It makes output with array('title','price','quantity'). Actually i want to put out each other and next save it in database.

array(1) { [52]=> array(3) { ["title"]=> string(11) "MacBook Pro" ["quantity"]=> int(1) 
["price"]=> string(7) "2399.99" } }

This is array, which i have in checkout page. Please help me. I want to put out each other, for example: $order_title = .... $order_price = ... $order_quantity = ... and next save it in database, table named 'orders'.

CodePudding user response:

Just insert / add the data how you do normally.

$carts = session('cart');

foreach($carts as $cart)
{
    Order::create([
       'order_title' => $cart['title'],
       'order_quantity' => $cart['quantity'],
       'order_price' => $cart['price'],
      
   ]);
}

CodePudding user response:

first read data from session then iterate through elements of array and save them:

$carts = session('cart');

foreach($carts as $cart) {
    $order = new Order();
    $order->order_title = $cart['title'];
    $order->order_quantity = $cart['quantity'];
    $order->order_price = $cart['price'];
    $order->save();
}
  • Related