| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
-
- namespace App\Http\Controllers;
-
- use App\Commerce\Cart;
- use App\Http\Controllers\Concerns\RendersStorefront;
- use App\Models\Product;
- use App\Models\Store;
- use Illuminate\Http\RedirectResponse;
- use Illuminate\Http\Request;
- use Illuminate\Validation\ValidationException;
- use Inertia\Response;
-
- /**
- * The shopper's cart for one store.
- */
- class CartController extends Controller
- {
- use RendersStorefront;
-
- public function show(Request $request, string $slug): Response
- {
- return $this->renderStorefront($request, $this->ownedStore($request, $slug), ['type' => 'cart']);
- }
-
- /**
- * Add a product to the cart.
- */
- public function add(Request $request, string $slug): RedirectResponse
- {
- $store = $this->ownedStore($request, $slug);
-
- $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' => __('This product is 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, string $slug, int $product): RedirectResponse
- {
- $store = $this->ownedStore($request, $slug);
-
- $validated = $request->validate([
- 'quantity' => ['required', 'integer', 'min:0', 'max:'.Cart::MAX_QUANTITY],
- ]);
-
- $this->cart($request, $store)->set($this->buyableProduct($store, $product), $validated['quantity']);
-
- return back();
- }
-
- public function remove(Request $request, string $slug, int $product): RedirectResponse
- {
- $store = $this->ownedStore($request, $slug);
-
- $this->cart($request, $store)->remove($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();
- }
- }
|