I am using Crinsane Laravel in my ecommerce project. I want to add the cart products as an order in the order
table. I have used foreach
function in the OrderController:
use AppModelsOrder; public function __construct(Order $order){ $this->order = $order; } public function store(Request $request) { foreach(Cart::content() as $row){ $data['product_id'] = $row->id; $data['price'] = $row->price; $data['quantity'] = $row->qty; $data['color_id'] = $row->options->color_id; $data['size_id'] = $row->options->size_id; $data['user_id'] = auth()->user()->id; $data['order_id'] = $request->order_id; $data['status'] = 'Processing'; $this->order->fill($data); $this->order->save(); } $notification = array( 'alert-type' => 'success', 'message' => 'Order submitted successfully.' ); Cart::destroy(); $order_id = $request->order_id; $order_detail = $this->order->with('products')->where('order_id', $order_id)->get(); return view('frontend.cod.success',compact('order_detail','notification','order_id')); }
But the above code only saves one product data in the database. What is wrong going here?
Edit
The output of dd(Cart::Content());
IlluminateSupportCollection {#463 ▼ #items: array:2 [▼ "adc28c54b34a48fc6a61151579c914ba" => GloudemansShoppingcartCartItem {#464 ▼ +rowId: "adc28c54b34a48fc6a61151579c914ba" +id: 114 +qty: 1 +name: "Air Cushion Damping Boys Sneakers Soft Bottom Sports Shoes 485" +price: 2000.0 +options: GloudemansShoppingcartCartItemOptions {#465 ▼ #items: array:4 [▼ "image" => "https://example.com/uploads/IMG_0939.png" "slug" => "air-cushion-damping-boys-sneakers-soft-bottom--sports-shoes-485" "color_id" => "5" "size_id" => "195" ] } -associatedModel: "AppModelsProduct" -taxRate: 0 -isSaved: false } "ed928a560633f9bab8a0d1ed5bb0ca20" => GloudemansShoppingcartCartItem {#466 ▼ +rowId: "ed928a560633f9bab8a0d1ed5bb0ca20" +id: 74 +qty: 1 +name: "ladies fashionable shoes" +price: 2000.0 +options: GloudemansShoppingcartCartItemOptions {#467 ▼ #items: array:4 [▼ "image" => "https://example.com/uploads/-31854440.jpg" "slug" => "ladies-fashionable-shoes" "color_id" => "5" "size_id" => "201" ] } -associatedModel: "AppModelsProduct" -taxRate: 0 -isSaved: false } ] }
Advertisement
Answer
Your issue is here:
foreach(Cart::content() as $row){ ... $this->order->fill($data); $this->order->save(); }
I am making some assumptions here, but It should look more like:
foreach (Cart::content() as $row){ ... $order = new Order(); $order->fill($data); $order->save(); }