How to Get Product Collection in Magento 2?

Blog Overview

In the previous blog, we learnt how to get customer collection in Magento 2. In this blog, we shall see how to get product collection in Magento 2.

Step 1 : Create the 2 mandatory files:

Refer this blog and create module.xml file inside etc folder and registration.php file inside Code5fixer/ProductCollection folder. Here, ProductCollection is the name of the module folder.

app/code/Code5fixer/ProductCollection/etc/module.xml
app/code/Code5fixer/ProductCollection/registration.php

Step 2 : Create a Controller file:

As a next step, we shall create a page using controller, in which we are going to display product collection in the frontend. To do so, create a folder inside CustomerCollection folder and name it as Controller. Inside Controller folder, create a folder and name it as Product and inside Customer folder, create a php file and name it as Index.php

The contents of Index.php file will be:

app/code/Code5fixer/ProductCollection/Controller/Product/Index.php

Index.php

<?php
namespace Code5fixer\ProductCollection\Controller\Product;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
     public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
     public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }
}

Step 3 :Create routes.xml file:

To make a Controller to work, we need routes.xml file inside frontend folder of the etc folder.

app/code/Code5fixer/ProductCollection/etc/frontend/routes.xml

The contents of routes.xml file will be:

routes.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="productcollection" id="productcollection">
            <module name="Code5fixer_ProductCollection"/>
        </route>
    </router>
</config>              

Remember, productcollection is the frontname and id.

Step 4 : Create a block file

Then, we shall create a block file on our custom module in the following path:

app/code/Code5fixer/ProductCollection/Block/ProductCollection.php

So, create a folder inside ProductCollection folder and name it as Block and inside Block folder create a php file and name it as ProductCollection.php

The contents of ProductCollection.php file will be :

<?php
namespace Code5fixer\ProductCollection\Block;
class ProductCollection 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(2); // fetching only 2 products
        return $collection;
    }
}
?>

Here, getProductCollection() returns the names of 2 products.

Step 5 : Create a template file :

Now, we need to create a phtml file to display the products in frontend. For that, create a folder inside ProductCollection module folder and name it as view. Inside view folder, create another folder and name it as frontend. Now, inside this frontend folder, create another folder and name it as templates. Inside this templates folder, create a phtml file and name it as productcollection.phtml

app/code/Code5fixer/ProductCollection/view/frontend/templates/productcollection.phtml

The content of productcollection.phtml

productcollection.phtml

<h1>Product List</h1>
<?php 
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getId()); 
    print_r($product->getName()); 
    print_r($product->getSKC());     
    echo "<br>";
}  

Step 6 : Create a layout file:

If we want to call a phtml file on a page then we need to create a layout file to achieve this. As a next move, let us create a folder inside view folder and name it as layout and inside this layout folder, create an xml file and name it as productcollection_product_index

Here, route id (specified in routes.xml)_name of the folder inside controller folder_action class must be the name of this layout file.

The contents of this layout file will be:

productcollection_product_index

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
    <body>
        <referenceContainer name="content">
            <block class="Code5fixer\ProductCollection\Block\ProductCollection" name="productcollection" template="productcollection.phtml" />
        </referenceContainer>
    </body>
</page>

Step 7 : Run all the necessary commands

We need to run commands like setup:upgrade, static-content:deploy, setup:di:compile, reindex and cache:flush from the Magento root directory.

To know more about more magento commands, refer this blog.

Let us open the below URL in our browser

http://<yourhost.com>/productcollection/product/index

And now, our browser will be as shown below.

We hope, with the help of the above steps, you will be easily getting the product collection in Magento2. Also, share this blog with your developer friends.

You could also download the above module here

After downloading this module:

  1. Extract the downloaded zip file
  2. Paste the extracted Code5fixer folder into /app/code/ folder in your magento root directory.
  3. Run all the necessary 5 commands and check for output.

This module is developed using Magento ver. 2.4.3-p1 version. But if you try this in older or newer versions, it may give some errors.

You could also refer to this demo video for better understanding.

We hope our guide would be very useful for you. If you have any questions, feel free to reach us anytime by leaving a comment below.

Check out our new blogs here

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments