How to Get Product Collection by Category Id in Magento 2

In this quick article, I am going to show you how to get a collection of products from the category in Magento 2. In the below example, I will be using both Dependency Injection (DI) and Object Manager methods to get the product collection.

Using Dependency Injection (DI)

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

To get the product collection from the category, we might need to inject the object of \Magento\Catalog\Model\CategoryFactory class in the constructor of our module’s class as follows,

Sample File Path: app/code/BlogTreat/MyModule/Block/MyBlock.php

<?php
namespace BlogTreat\MyModule\Block;

class MyBlock extends \Magento\Framework\View\Element\Template {

    /**
     * @var \Magento\Catalog\Model\CategoryFactory
     */
    protected $categoryFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Model\CategoryFactory $categoryFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,        
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        array $data = []
    ) {    
        $this->categoryFactory = $categoryFactory;
        parent::__construct($context, $data);
    }

    /**
     * @param $categoryId
     * @return mixed
     */
    public function getProductsByCategoryId($categoryId) {

        // get category information by using category id
        $category = $this->categoryFactory->create()->load($categoryId);

        // get assigned products from category
        $products = $category->getProductCollection();
        $products->addAttributeToSelect('*');
        return $products;
    }
}

Now, we can call the function getProductsByCategoryId($categoryId) in our view (.phtml) file as follows,

$categoryId = 10;
$products = $block->getProductsByCategoryId($categoryId);
foreach ($products as $product) {
    echo $product->getName() . ' - ' . $product->getSku() . '<br />';
}

Using Object Manager

Here is the example to get the list of products from the category in Magento 2 using Object Manager,

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

$categoryId = 1033;
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();
$category = $categoryFactory->load($categoryId);

$products = $category->getProductCollection()
                    ->addAttributeToSelect('*');

foreach ($products as $product) {
    echo $product->getName() . ' - ' . $product->getSku() . '<br />';
}

Get Product Collection by Multiple Categories

In some cases, we may need to get the product collection using multiple category ids. It’s also possible and here is the code which will help you,

Using Dependency Injection (DI)

Here is the example to get the list of products using multiple category ids in Magento 2 by dependency injection,

/**
 * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
 */
protected $productCollectionFactory;

/**
 * @param \Magento\Framework\View\Element\Template\Context $context
 * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
 * @param array $data
 */
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    array $data = []
) {
    $this->productCollectionFactory = $productCollectionFactory;
    parent::__construct($context, $data);
}

/**
 * @param $ids
 * @return mixed
 */
public function getProductsByCategoryIds($ids) {
    $products = $this->productCollectionFactory->create();
    $products->addAttributeToSelect('*');
    $products->addCategoriesFilter(['in' => ids]);
    return $products;
}

Now, we can call the function getProductsByCategoryIds($ids) in our view (.phtml) file as follows,

$ids = [1,2,3];
$products = $block->getProductsByCategoryIds($ids);
foreach ($products as $product) {
    echo $product->getName() . ' - ' . $product->getSku() . '<br />';
}

Using Object Manager

Here is the example to get the list of products using multiple category ids in Magento 2 by Object Manager,

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

$ids = [1,2,3];
$collectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
$products = $collectionFactory->addAttributeToSelect('*')
                            ->addCategoriesFilter(['in' => $ids]);

foreach ($products as $product) {
    echo $product->getName() . ' - ' . $product->getSku() . '<br />';
}

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 *