Magento – How to get recently viewed products collection of Customer Magento 2

magento2product-collectionrecently-viewed

Magento 2 get recently viewed products collection of Customer (Using customer ID) programmatically

I tried this solution But I want recently viewed products collection.

I tried below solution too but it is not returning anything. [I am logged in]

protected $recentlyViewed;

public function __construct(
...
    \Magento\Reports\Block\Product\Viewed $recentlyViewed
) {
...
    $this->recentlyViewed = $recentlyViewed;
}

/**
 * Get recently viewed products for the customer
 *
 */
public function getMostRecentlyViewed(){
    return $this->recentlyViewed->getItemsCollection();
}

Best Answer

Try to use this code :

Method 1 :

/**
 * Layout
 * @var \Magento\Framework\View\LayoutInterface
 */

 protected $_layout;

 public function __construct(
    .....
    \Magento\Framework\View\LayoutInterface $layout
    .......
 ) {
     $this->_layout = $layout;
 }

public function getMyCollection() {
    $block =  $this->_layout->getBlockSingleton(\Magento\Reports\Block\Product\Viewed::class)->getItemsCollection();
    return $block;
}

UPDATE :

Method 2 :

You need to load ItemCollection() after get collection like below way :

protected $recentlyViewed;

public function __construct(
    \Magento\Reports\Block\Product\Viewed $recentlyViewed
) {
    $this->recentlyViewed = $recentlyViewed;
}

public function execute() {
    $collection = $this->recentlyViewed->getItemsCollection()->load();
    echo "<pre>";
    print_r($collection->getData());
    exit;
}

Reference

Related Topic