/** * Returns the cart item for a given inventory * * @param \Bedard\Shop\Models\Inventory $inventory * @return \Bedard\Shop\Models\CartItem */ public function getCartItem(Inventory $inventory) { $this->persistCart(); $item = CartItem::firstOrNew(['cart_id' => $this->cart->id, 'product_id' => $inventory->product_id, 'inventory_id' => $inventory->id]); $item->setRelation('inventory', $inventory); return $item; }
/** * Adds a product to the cart */ public function onAddToCart() { // Make a cart if we don't have one if (!$this->cart) { $this->makeCart(); } // Load the post variables that may have come in $slug = post('bedard_shop_product'); $inventoryId = post('bedard_shop_inventory'); $quantity = post('bedard_shop_quantity') ?: 1; // Load the inventory if (!($inventory = $this->loadInventory($inventoryId, $slug))) { return $this->failedResponse('Inventory not found.'); } // FirstOrCreate the cart item, and add the quantity $cartItem = CartItem::firstOrNew(['cart_id' => $this->cart->id, 'inventory_id' => $inventory->id]); if ($cartItem->quantity >= $inventory->quantity) { $this->itemCount = CartItem::where('cart_id', $this->cart->id)->sum('quantity'); $this->isEmpty = $this->itemCount == 0; return $this->failedResponse('All available inventory is already in your cart.'); } // Update and save the cart item quantity $cartItem->quantity += $quantity; if (!$cartItem->save()) { $this->itemCount = CartItem::where('cart_id', $this->cart->id)->sum('quantity'); $this->isEmpty = $this->itemCount == 0; return $this->failedResponse('Failed to save cart item.'); } // Restart the checkout process $this->restartCheckoutProcess(); // Refresh the item count, and send back a response $this->itemCount = CartItem::where('cart_id', $this->cart->id)->sum('quantity'); $this->isEmpty = $this->itemCount == 0; return $this->response('Product added to cart'); }