carts() ->with(['product' => function ($query) { $query->with(['media', 'channels']); }]) ->get() ->each(function ($cart) use ($order) { // Create Order Item DB::table('order_items')->insert([ 'product_name' => $cart->product->name, 'product_id' => $cart->product_id, 'order_id' => $order->id, 'channel_id' => $cart->product->channels->first()?->id ?? tmpostChannel()->id, 'quantity' => $cart->product_quantity, 'unit_price_amount' => $cart->product->price_amount, 'unit_cost_amount' => $cart->product->cost_amount, 'created_at' => now(), 'updated_at' => now(), ]); // Update Stock directly in products table, also relationship $stock = $cart->product->stock - $cart->product_quantity; $cart->product->update([ 'stock' => $stock, ]); $data = DB::table('inventory_product')->where('product_id', $cart->product_id)->first(); if ($data) { DB::table('inventory_product')->where('id', $data->id)->update([ 'stock' => $stock, ]); } else { warn('Product has no inventory record', json_encode([ 'product_id' => $cart->product_id, 'order_id' => $order->id, ])); } }); // 3. Clear User Cart $user->carts()->delete(); // 4. Dispatch Event OrderCreated::dispatch($order); return $order; }); } }