Mitech Preloader
Magento / Magento2

How to get Product collection in Magento 2?

Get Product Collection in Magento 2

Here We will know, How to get Product collection in Magento 2, as a Magento Development Company  We have to use this get Product Collection formulas again and again in each and every project, So Here we will see all formulas to get Product collection using Object Manager.

Get product collection

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

foreach ($collection as $product) {
    print_r($product->getData());
}

Get product collection with all attribute

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(2);

foreach ($collection as $product) {
    print_r($product->getData());
}

Get product collection by category

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryId = '3'; // Particular Category ID
$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) {
    print_r($product->getData());
}

Get product collection with a particular attribute

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('isfeatured'); //Attribute Code
$collection->addAttributeToSelect('displayonhomepage'); //Attribute Code
$collection->setPageSize(2);

foreach ($collection as $product) {
    print_r($product->getData());
}

All are done here to get Product collection in Magento 2 using object manager. I hope this will help you.

blank