| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
-
- namespace App\Http\Controllers;
-
- use App\Commerce\Cart;
- use App\Http\Controllers\Concerns\RendersStorefront;
- use App\Models\Product;
- use App\Models\Store;
- use App\Storefront\StorefrontText;
- use Illuminate\Http\RedirectResponse;
- use Illuminate\Http\Request;
- use Illuminate\Validation\ValidationException;
- use Inertia\Response;
-
- /**
- * The shopper's cart for one store. Used for both the live store and the owner's preview.
- */
- class CartController extends Controller
- {
- use RendersStorefront;
-
- public function show(Request $request): Response
- {
- return $this->renderStorefront($request, $this->storefront($request), ['type' => 'cart']);
- }
-
- /**
- * Add a product to the cart.
- */
- public function add(Request $request): RedirectResponse
- {
- $store = $this->storefront($request)->store;
-
- $validated = $request->validate([
- 'product_id' => ['required', 'integer'],
- 'quantity' => ['required', 'integer', 'min:1', 'max:'.Cart::MAX_QUANTITY],
- ]);
-
- $product = $this->buyableProduct($store, $validated['product_id']);
-
- if ($product->stock < 1) {
- throw ValidationException::withMessages(['quantity' => StorefrontText::line($store->language->value, 'sold_out')]);
- }
-
- $this->cart($request, $store)->add($product, $validated['quantity']);
-
- return back();
- }
-
- /**
- * Change how many of a product are in the cart. Zero removes it.
- */
- public function update(Request $request): RedirectResponse
- {
- $store = $this->storefront($request)->store;
-
- $validated = $request->validate([
- 'quantity' => ['required', 'integer', 'min:0', 'max:'.Cart::MAX_QUANTITY],
- ]);
-
- $this->cart($request, $store)->set($this->buyableProduct($store, (int) $request->route('product')), $validated['quantity']);
-
- return back();
- }
-
- public function remove(Request $request): RedirectResponse
- {
- $store = $this->storefront($request)->store;
-
- $this->cart($request, $store)->remove((int) $request->route('product'));
-
- return back();
- }
-
- /**
- * A product of this store that shoppers may buy. Anything else gives "not found".
- */
- private function buyableProduct(Store $store, int $id): Product
- {
- return $store->products()->active()->whereKey($id)->firstOrFail();
- }
- }
|