How to Add Pagination in Magento 2 Custom Collection (Step-By-Step)

For any website, user experience matters first. What user feels about the site or store plays a vital role in site's success. And that's why one needs to focus on many factors for the best user experience. And one of them is Pagination. To add pagination on the site gives better look to it. Moreover, the site does not look messy or saturated. Pagination helps to serve the site content in a better format. Thus, visitors can easily find out what actually they want. So, without wasting time, let's directly jump on How to add pagination in Magento 2.

How to Add Pagination in Magento 2

⇒ There are 4 steps to add pagination. You can use the below code step-wise to add pagination to your Magento 2  store:

how to add pagination in Magento 2

1.Pager Collection Creation

protected $categorycollectionFactory;
 public function __construct(\Store\Blog\Model\ResourceModel\Category\CollectionFactory $categorycollectionFactory) 
    { 
        $this->categorycollectionFactory = $categorycollectionFactory; 
    }
 public function getCategory()
    {
        $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
        $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;
        $categorycollection = $this->categorycollectionFactory->create();
        $categorycollection->setPageSize($pageSize);
        $categorycollection->setCurPage($page);
        return $categorycollection;
    }

2. Set Limit for Pager

protected function _prepareLayout()
 {
     parent::_prepareLayout();
     $this->pageConfig->getTitle()->set(__('Categories'));
     if ($this->getNews()) {
         $pager = $this->getLayout()->createBlock(
            'Magento\Theme\Block\Html\Pager',
            'store.category.pager'
         )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection(
            $this->getCategory()
         );
         $this->setChild('pager', $pager);
         $this->getCategory()->load();
     }
     return $this;
 }

3. Child Block

public function getPagerHtml()
{
    return $this->getChildHtml('pager');
}

4. Call the Pager

<?php if ($block->getPagerHtml()): ?>
    <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div>
<?php endif ?>

⇒ That's it!

⇒ Now, offer ease to the visitors by adding pagination to your Magento 2 site.

⇒ Your queries and concerns are most welcome at support@milople.com