2

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

1

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>";
}
  • please explain how you have used logic for latest products.. i am not getting that – Waqar Ali May 8 at 9:41
  • updated the answer with sort order – fmsthird May 8 at 9:46
  • 1
    thank you its working – Waqar Ali May 8 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.