File manager - Edit - /home/webapp69.cm.in.th/u69319090017/shop17/app/Services/CheckoutService.php
Back
<?php namespace App\Services; use App\Models\Order; use App\Models\OrderItem; use App\Models\User; use App\Models\CartItem; use App\Models\ProductVariant; use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; class CheckoutService { /** * Place order from cart items. * * @throws ValidationException */ public function placeOrder(User $user): Order { return DB::transaction(function () use ($user) { $cartItems = CartItem::with(['variant.product'])->where('user_id', $user->id)->get(); if ($cartItems->isEmpty()) { throw ValidationException::withMessages([ 'cart' => 'Your cart is empty.', ]); } $totalAmount = 0; $itemsToCreate = []; foreach ($cartItems as $item) { $variant = ProductVariant::lockForUpdate()->find($item->product_variant_id); if (!$variant || $variant->stock < $item->quantity) { throw ValidationException::withMessages([ 'stock' => "Insufficient stock for '{$variant->name}'. Available: {$variant->stock}.", ]); } // Decrease stock $variant->decrement('stock', $item->quantity); $itemTotal = $variant->price * $item->quantity; $totalAmount += $itemTotal; $itemsToCreate[] = [ 'shop_id' => $variant->product->shop_id, 'product_variant_id' => $variant->id, 'quantity' => $item->quantity, 'price' => $variant->price, 'shipping_status' => 'Pending', ]; } // Create Order $order = Order::create([ 'buyer_id' => $user->id, 'total_amount' => $totalAmount, 'status' => 'pending', ]); // Create Order Items foreach ($itemsToCreate as $itemData) { $order->items()->create($itemData); } // Clear Cart CartItem::where('user_id', $user->id)->delete(); return $order; }); } }
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | Generation time: 0.26 |
proxy
|
phpinfo
|
Settings