AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CartController.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commerce\Cart;
  4. use App\Http\Controllers\Concerns\RendersStorefront;
  5. use App\Models\Product;
  6. use App\Models\Store;
  7. use App\Storefront\StorefrontText;
  8. use Illuminate\Http\RedirectResponse;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Validation\ValidationException;
  11. use Inertia\Response;
  12. /**
  13. * The shopper's cart for one store. Used for both the live store and the owner's preview.
  14. */
  15. class CartController extends Controller
  16. {
  17. use RendersStorefront;
  18. public function show(Request $request): Response
  19. {
  20. return $this->renderStorefront($request, $this->storefront($request), ['type' => 'cart']);
  21. }
  22. /**
  23. * Add a product to the cart.
  24. */
  25. public function add(Request $request): RedirectResponse
  26. {
  27. $store = $this->storefront($request)->store;
  28. $validated = $request->validate([
  29. 'product_id' => ['required', 'integer'],
  30. 'quantity' => ['required', 'integer', 'min:1', 'max:'.Cart::MAX_QUANTITY],
  31. ]);
  32. $product = $this->buyableProduct($store, $validated['product_id']);
  33. if ($product->stock < 1) {
  34. throw ValidationException::withMessages(['quantity' => StorefrontText::line($store->language->value, 'sold_out')]);
  35. }
  36. $this->cart($request, $store)->add($product, $validated['quantity']);
  37. return back();
  38. }
  39. /**
  40. * Change how many of a product are in the cart. Zero removes it.
  41. */
  42. public function update(Request $request): RedirectResponse
  43. {
  44. $store = $this->storefront($request)->store;
  45. $validated = $request->validate([
  46. 'quantity' => ['required', 'integer', 'min:0', 'max:'.Cart::MAX_QUANTITY],
  47. ]);
  48. $this->cart($request, $store)->set($this->buyableProduct($store, (int) $request->route('product')), $validated['quantity']);
  49. return back();
  50. }
  51. public function remove(Request $request): RedirectResponse
  52. {
  53. $store = $this->storefront($request)->store;
  54. $this->cart($request, $store)->remove((int) $request->route('product'));
  55. return back();
  56. }
  57. /**
  58. * A product of this store that shoppers may buy. Anything else gives "not found".
  59. */
  60. private function buyableProduct(Store $store, int $id): Product
  61. {
  62. return $store->products()->active()->whereKey($id)->firstOrFail();
  63. }
  64. }