:::: MENU ::::

Magento 2 get product collection

Magento 2 get product collection

Today we talk about Magento 2 get product collection. First we need to familiar with model collection structure of magento 2. Magento 2 use the collection class for get all record from database table. SO let start with coding. We are using the Factory method here.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      return   $this->_productCollectionFactory->create()->addAttributeToSelect('*');
     
     }

To Fetch Data in phtml file

$productCollection = $block->getProductCollection();

foreach ($productCollection as $product) {

   
        echo $product->getName().'<br />';

}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


3 Comments

    • Reply qaisarsatti |

      Thanks for your feedback but it is not necessary for this tutorial. because the tutorial is general not specific to block or etc.

So, what do you think ?