-
app/Cart.php
Open in GitHubuse App\Product; use Illuminate\Database\Eloquent\Model; class Cart extends Model { // public function products() { return $this->morphToMany(Product::class, 'productable')->withPivot('quantity'); } // }
-
app/Product.php
Open in GitHubuse App\Cart; use Illuminate\Database\Eloquent\Model; class Product extends Model { // public function carts() { return $this->morphedByMany(Cart::class, 'productable')->withPivot('quantity'); } // }
-
app/Http/Controllers/OrderController.php
Open in GitHubuse App\Services\CartService; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; class OrderController extends Controller { public $cartService; public function __construct(CartService $cartService) { $this->cartService = $cartService; $this->middleware('auth'); } // public function store(Request $request) { return DB::transaction(function() use($request) { $user = $request->user(); $order = $user->orders()->create([ 'status' => 'pending', ]); $cart = $this->cartService->getFromCookie(); $cartProductsWithQuantity = $cart ->products ->mapWithKeys(function ($product) { $quantity = $product->pivot->quantity; if ($product->stock < $quantity) { throw ValidationException::withMessages([ 'cart' => "There is not enough stock for the quantity you required of {$product->title}", ]); } $product->decrement('stock', $quantity); $element[$product->id] = ['quantity' => $quantity]; return $element; }); $order->products()->attach($cartProductsWithQuantity->toArray()); return redirect()->route('orders.payments.create', ['order' => $order->id]); }, 5); } }