Today we talk about Magento 2 get product collection. First we need to familiar with model collection structure of magento 2. Magento 2 use the collection class for get all record from database table. SO let start with coding. We are using the Factory method here.
protected $_productCollectionFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
) {
$this->_productCollectionFactory = $productFactory;
}
public function getProductCollection()
{
return $this->_productCollectionFactory->create()->addAttributeToSelect('*');
}
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
) {
$this->_productCollectionFactory = $productFactory;
}
public function getProductCollection()
{
return $this->_productCollectionFactory->create()->addAttributeToSelect('*');
}
To Fetch Data in phtml file
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
echo $product->getName().'<br />';
}
foreach ($productCollection as $product) {
echo $product->getName().'<br />';
}