I want to get Collection of Latest Products in Magento 2 i have some restriction
- Without using Object Manager
- Without using API
i have searched on internet found these two methods but i have to avoid using them
You can create a Block class and inject Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
in the constructor and you can get/display product collection in phtml
file.
Check below code:
<?php
namespace Vendor\Module\Block;
class ProductDisplay extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(5); // fetching only 3 products
$colletion->setOrder('created_at','DESC'); //sort by date created
return $collection;
}
}
In your phtml
file:
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
print_r($product->getData());
echo "<br>";
}