Tutorialsplane

Magento 2 get Product Collection


Magento 2 get Product Collection : In magento 1.x we get product collection using the Mage::getModel(‘catalog/product’)->getCollection(); but in magento 2.0 it is different to get the product collection. Here in this tutorial we are going to explain how to get product collection in magento 2.


Magento 2 get Product Collection

You can get product collection in magento 2.0 as below-

Magento 2 get Product Collection:

<?php //$productId = 100;
$sku = "testsku";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$prodCollection = $objectManager-?>create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $prodCollection->create()
            ->addAttributeToSelect('*')
            ->addFieldToFilter('sku',$sku);
             // or ->load($productId);
foreach ($collection as $product){
     echo 'Name =  '.$product->getName().'<br/>';
	 echo 'Id  =  '.$product->getId().'<br/>';
	 echo 'Sku  =  '.$product->getSku().'<br/>';
}  

?>

The above example will give the product collection of by the sku or you can simply load the collection by product id simply using the ->load($productId) method.