middleware([ RedirectIfCartIsEmpty::class, ]); $this->middleware([ CheckCartItemsStock::class, ])->only('store'); } /** * Store a newly created resource in storage. * * @param StoreOrderRequest $request * @param CustomerService $customerService * @param OrderService $orderService * * @return JsonResponse */ public function store(StoreOrderRequest $request, CustomerService $customerService, OrderService $orderService) { if (auth()->guest() && $request->create_an_account) { $customerService->register($request)->login(); } $cartWithCoupon = null; $couponCode = request()->query('coupon_code'); if ($couponCode) { $coupon = Coupon::findByCode($couponCode); try { resolve(Pipeline::class) ->send($coupon) ->through($this->checkers) ->then(function ($coupon) use (&$cartWithCoupon) { Cart::applyCoupon($coupon); }); } catch (Exception) { //Just suppressing the exception } } $order = $orderService->create($request); $gateway = Gateway::get($request->payment_method); try { $response = $gateway->purchase($order, $request); } catch (Exception $e) { $orderService->delete($order); return response()->json([ 'message' => $e->getMessage(), ], 403); } finally { if (Cart::hasCoupon()) { Cart::removeCoupon(); } } return response()->json($response); } /** * Show the form for creating a new resource. * * @return Application|Factory|View */ public function create(): View|Factory|Application { Gateway::all(); return view('public.checkout.create', [ 'cart' => Cart::instance(), 'countries' => Country::supported(), 'gateways' => Gateway::all(), 'defaultAddress' => auth()->user()->defaultAddress ?? new DefaultAddress, 'addresses' => $this->getAddresses(), 'termsPageURL' => Page::urlForPage(setting('storefront_terms_page')), ]); } /** * Get addresses for the logged in user. * * @return Collection */ private function getAddresses() { if (auth()->guest()) { return collect(); } return auth()->user()->addresses->keyBy('id'); } }