Magento 2: Get Product Collection

This article shows how we can get product collection in Magento 2.

Using Dependency Injection (DI)

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory class in the constructor of my module’s block class.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php


<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{	
	protected $_productCollectionFactory;
		
	public function __construct(
		\Magento\Backend\Block\Template\Context $context,		
		\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,		
		array $data = []
	)
	{	
		$this->_productCollectionFactory = $productCollectionFactory;	
		parent::__construct($context, $data);
	}
	
	public function getProductCollection()
	{
		$collection = $this->_productCollectionFactory->create();
		$collection->addAttributeToSelect('*');
		$collection->setPageSize(3); // fetching only 3 products
        return $collection;
	}
}
?>

As you can see in above code, I have addded limit to the product collection. I have selected only 3 products.

Now, we print the product collection in our template (.phtml) file.


$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
	print_r($product->getData()); 	
	echo "<br>";
}

Using Object Manager


$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();		

$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // selecting only 3 products

foreach ($collection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

Hope this helps. Thanks.