$user->orders]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Request $request) { $validated = $request->validate([ 'products' => 'required|array', 'products.*' => 'exists:products,uuid', 'product_quantities' => 'required|array', 'product_quantities.*' => 'numeric|min:1', ]); $products_quantities = array_map(fn ($v, $q) => [Product::query()->where("uuid", $v)->first(), $q], $validated["products"], $validated["product_quantities"]); return view("order/create", ["products_with_quantities" => $products_quantities]); // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $user = Auth::user(); if (!$user) { throw new AccessDeniedHttpException("Not logged in"); } $validated = $request->validate([ 'products' => 'required|array', 'products.*' => 'exists:products,uuid', 'product_quantities' => 'required|array', 'product_quantities.*' => 'numeric|min:1', 'address' => 'required', ]); $products_quantities = array_map(fn ($v, $q) => [Product::query()->where("uuid", $v)->first(), $q], $validated["products"], $validated["product_quantities"]); DB::transaction(function () use ($validated, $user, $products_quantities) { $address = new Address($validated); $address->user()->associate($user); $address->save(); $order = new Order(); $order->address()->associate($address); $order->user()->associate($user); $order->cost = array_reduce($products_quantities, fn ($c, $i) => bcadd($c,bcmul($i[0]->price,$i[1])), 0); $order->save(); foreach($products_quantities as $product_quantity) { $product = $product_quantity[0]; $quantity = $product_quantity[1]; $order->products()->attach($product); $order->products()->find($product->uuid)->pivot->quantity = $quantity; } }); foreach($products_quantities as $product) { $user->cart()->detach($product[0]); } return redirect()->route("order.index"); } /** * Display the specified resource. * * @return \Illuminate\Http\Response */ public function show(Order $order) { // } /** * Show the form for editing the specified resource. * * @return \Illuminate\Http\Response */ public function edit(Order $order) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function update(Request $request, Order $order) { $validated = $request->validate([ 'address' => 'string', ]); if (isset($validated["address"])) { $address = $order->address()->withDefault(fn () => new Addres($validated)); $address->address = $validated["address"]; $order->save(); } } /** * Remove the specified resource from storage. * * @return \Illuminate\Http\Response */ public function destroy(Order $order) { throw new Error("TODO"); // } }