Magento 2 best Seller product collection

Let’s talk about using sales report collection so today we talk about how to get Magento 2 best seller product collection. Best seller collection in depend on number of time product quantity is sold. First we have to inject the Bestsellers\CollectionFactory in you block or helper any other file you want to use it. You can get the report of monthly,yearly and daily and also custom date. So let start with coding. In this example I am going to inject into my block.

Step 1: Create a block file

<?php
    /**
    * Simple Hello World Module
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       qaisarssatti@gmail.com
    *
    */

namespace QaisarSatti\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{
 
    protected $_collectionFactory;
   public function __construct(
       \Magento\Backend\Block\Template\Context $context,
      \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
               array $data = []
   ) {
 
       $this->_collectionFactory = $collectionFactory;
             parent::__construct($context, $data);
   }


public function getBestSellerData(){
     
$bestSellerProdcutCollection = $this->_collectionFactory->create()
                    ->setModel('Magento\Catalog\Model\Product')
                    ->setPeriod('month') //you can add period daily,yearly
                   ;
           
       return $bestSellerProdcutCollection;
   }
}

Step 2: Show Output

Getting collection in phtml file from block.

<!--/**
    * Simple Hello World Module
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       qaisarssatti@gmail.com
    *
    */
-->

    <?php
        $bestSeller =  $block->getBestSellerData(); ?>
        <h1>Best Seller Collection.....</h1>
        <ul>
            <?php foreach ($bestSeller as $product) {
                ?>
                <li><?php  echo $product->getProductName();?>--<?php  echo $product->getQtyOrdered();?></li>
            <?php } ?>
</ul>

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

2 thoughts on “Magento 2 best Seller product collection

Leave a Reply