Tutorialsplane

Magento 2 Collection get last Item


Magento 2 Collection get last Item: There are many ways to get last item from Magento collection. Here in this article we are going to explain one of the method to get last item from collection using order by and setPageSize.


Magento 2 Collection get last Item Example

You can add order by desc and setPageSize to get the last item from the collection. Here is an example to get last item-

Magento 2 Collection get last Item Example:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();   
$firstItem = $objectManager->create('Mypackage\MyModule\Model\MyData')
                    ->getCollection()
                    ->setOrder('id DESC')
                    ->setPageSize('1');

The above example will give last item so on the same way you can get the first item by just adding ->setOrder(‘id ASC’)