get product collection

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

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


namespace Mtutorials\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->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) {
    echo "<br>";

Using Object Manager

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$appState = $objectManager->get('\Magento\Framework\App\State');
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->setPageSize(3); // selecting only 3 products
foreach ($collection as $product) {
    echo "<br>";

Hope this will helps you!

Leave a Reply

Your email address will not be published. Required fields are marked *