Hello Everyone,

In this blog, we will learn about how to get Product Collection in Magento 2.

Product Collection means showing the items in your Magento 2 Store when you run the command.

Without wasting your time, let us guide you straight away. Follow the easy step given below to get Product Collection in Magento 2.

STEPS FOR GET PRODUCT COLLECTION IN MAGENTO 2

Step 1: Create Hello.php file

app/code/Vendor/Extension/Block/Hello.php

<?php

namespace Vendor\Extension\Block;

class Hello extends \Magento\Framework\View\Element\Template

{

          protected $productFactory;

    public function __construct(

        \Magento\Backend\Block\Template\Context $context,

        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory,

        array $data = []

    )

    {

        $this->productFactory = $productFactory;

        parent::__construct($context, $data);

    }

    public function getProductCollection()

    {

        $collection = $this->productFactory->create();

        return $collection;

    }

}

Now We Print Product Collection in .phtml file. We call getProductCollection() method from our block.

<?php

$productCollection = $block->getProductCollection();

foreach ($productCollection as $product) {

    echo “<pre>”;

    print_r($product->getData());

    echo “</pre>”;

}

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can get Product Collection in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

Leave a Reply

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