How to Get Product Collection in Magento 2?

In this quick article, I am going to show you how to get the list of all products in Magento 2 programmatically.

Here, I will be giving the example in both Dependency Injection (DI) method and Object Manager method to get the product collection in Magento 2.

Using Dependency Injection (DI)

Here is the example code to get the list of all products in Magento 2 using dependency injection.

In order to get the product collection in Magento 2, we might need to inject the object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory class in the constructor of our module’s block class and access it from the view (.phtml) file.

Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php

<?php
namespace YourCompanyName\YourModuleName\Block;

class YourCustomBlock extends \Magento\Framework\View\Element\Template
{ 
    protected $_productCollectionFactory;
  
    protected $_productVisibility;
  
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context, 
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\Product\Visibility $productVisibility,
        array $data = []
    ) {
        $this->_productCollectionFactory = $productCollectionFactory; 
        $this->_productVisibility = $productVisibility; 
        parent::__construct($context, $data);
    }
  
    public function getProductCollection() {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
  
        // filter current website products
        $collection->addWebsiteFilter();
 
        // filter current store products
        $collection->addStoreFilter();
  
        // set visibility filter
        $collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
  
        // fetching only 5 products
        $collection->setPageSize(5); 
  
        return $collection;
    }
}

Now, we can use the functions in our view (.phtml) file as follows.

$productCollection = $block->getProductCollection(); 
foreach ($productCollection as $product) { 
    echo $product->getId() . '<br />';
    echo $product->getName() . '<br />';
}

Using Object Manager

Here is the code to get the list of all products in Magento 2 using Object Manager.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
  
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
 
// filter current website products
$collection->addWebsiteFilter();
 
// filter current store products
$collection->addStoreFilter();
 
// set visibility filter
$collection->setVisibility($objectManager->get('\Magento\Catalog\Model\Product\Visibility')->getVisibleInSiteIds());
 
// fetching only 5 products
$collection->setPageSize(5); 
foreach ($productCollection as $product) { 
    echo $product->getId() . '<br />';
    echo $product->getName() . '<br />';
}

Find below some different ways to get product collection in Magento 2. Here, I have given the example in the object manager method for the demo purpose,

Get Product Collection With All Attribute

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(5);
 
foreach ($collection as $product) {
    echo $product->getId() . '<br />';
    echo $product->getName() . '<br />';
}

Get Product Collection With Specific Attribute

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('price');
$collection->setPageSize(5);
 
foreach ($collection as $product) {
    echo $product->getId() . '<br />';
    echo $product->getName() . '<br />'; 
}

Get Product Collection by Category

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
 
$categoryId = '5';
$category = $categoryCollectionFactory->create()->load($categoryId);
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
 
foreach ($collection as $product) {
    echo $product->getId() . '<br />';
    echo $product->getName() . '<br />'; 
}

Filter Product Collection

Is equal to

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('status', array('eq' => 1));

Is not equal to

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('status', array('neq' => 1));

Greater than

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('price', array('gt' => 100));

Greater than or equal to

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('price', array('gteq' => 100));

Less than

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('price', array('lt' => 100));

Less than or equal to

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('price', array('lteq' => 100));

Like

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('sku', array('like' => '%Test%'));

Not like

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('sku', array('nlike' => '%Test%'));

In array

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', array('in' => array(1,2,3)));

Not in array

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', array('nin' => array(1,2,3)));

NULL

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('description',  array('null' => true));

Not NULL

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('description',  array('notnull' => true));

Sort Product Collection

Order by ascending

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->setOrder('price', 'ASC');

Order by descending

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->setOrder('price', 'DESC');

Limit Product Collection

Limit

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->setPageSize(50)->load();

Limit with current page

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->setPageSize(50)->setCurPage(2)->load();

Read Also: How to Get Category Collection in Magento 2?

Hope this helps.

Leave a Reply

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