cartItemFactory = $cartItemFactory; $this->_customerRepositoryInterface = $customerRepositoryInterface; $this->request = $request; $this->objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $this->customerSession = $this->objectManager->get(\Magento\Customer\Model\Session::class); parent::__construct($context); } private function getCartItems($customerId) { $collection = $this->cartItemFactory->create()->getCollection(); $data = $collection->addFieldToFilter('customer_id', ['eq' => $customerId]) ->setOrder('name','ASC') ->getData(); return $data; } private function isCartItem($item) { $collection = $this->cartItemFactory->create()->getCollection(); $count = $collection->addFieldToSelect('id') ->addFieldToFilter('customer_id', ['eq' => $item["customer_id"]]) ->addFieldToFilter('product_id', ['eq' => $item["product_id"]]) ->count(); if ($count > 0) { return true; } return false; } private function addCartItem($item, $customer) { if (!$this->isCartItem($item)) { $data = $this->cartItemFactory->create()->addData([ 'email' => $customer->getEmail(), 'name' => $item["name"], 'sku' => $item["sku"], 'product_id' => $item["product_id"], 'qty' => $item["qty"], 'customer_id' => $customer->getId(), 'price' => $item["price"], 'url' => $item["url"], 'image' => $item["image"] ])->save(); return $data; } return null; } public function execute() { $data = json_decode(file_get_contents('php://input'), TRUE); if($this->customerSession->isLoggedIn()) { $customer = $this->customerSession->getCustomer(); $this->addCartItem($data, $customer); echo json_encode($this->getCartItems($customer->getId())); exit; } else { echo json_encode(array()); } } }