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 />';

}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

3 thoughts on “Magento 2 get product collection

Leave a Reply