How to Remove Products from Compare Collection in Magento2

comparemagento2

Looking for a better way to add and remove the product on click of same icon.

If a product is already added to the compare collection then on next click of that icon, It should remove the product from compare collection.

Best Answer

protected  $_productloader;
protected $_compareItemFactory;
protected $_catalogProductCompareList;

public function __construct(
    \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory,
    \Magento\Catalog\Model\Product\Compare\ListCompare $catalogProductCompareList,
    \Magento\Catalog\Model\ProductFactory $productloader
) {
    $this->_productloader = $productloader;
    $this->_compareItemFactory = $compareItemFactory;
    $this->_catalogProductCompareList = $catalogProductCompareList;
}

public function execute()
{
    $productId = (int)$this->getRequest()->getParam('product');
    $product=$this->_productloader->create()->load($productId);
    $compareitem=$this->_compareItemFactory->create()->loadByProduct($product);
    if($compareitem):
    $this->_catalogProductCompareList->removeProduct($product);
    else:
    $this->_catalogProductCompareList->addProduct($product);
    endif;
}
Related Topic