I want to retrieve the last and first item from model collection in magento 2, in magento 1.9 i can simply retrieve it like this :

$lastItem = $collections->getLastItem();
$firstItem = $collections->getFirstItem();

is there a way i can do the same in magento 2, without using foreach loop like this:

$collections = $this->_objectManager->create('Namespace\Module\Model\Test')->getCollection(); 
foreach($collections as $collection){
  if($i == 0){
    $firstItem = $collection;
  } else{
    $lastItem = $collection;
  • 2
    $lastItem = $collections->getLastItem(); and $firstItem = $collections->getFirstItem(); is not working?
    – Amit Bera
    Commented Mar 13, 2017 at 3:52

2 Answers 2


This is Tested Solution feel free to implement

$firstItem = $collections->getFirstItem();
$lastItem = $collections->getLastItem();

echo 'This First Record in Collection <br> ';


echo '<br> This LastRecord in Collection <br> ';


If you don't want to use a for-each loop then you should use the below code to get First and Last Item.

For First Item, you can use an array of 0. e.g $collection[0]. This will give you the first element of your array.

For the Last Item, you can reverse the array and then use the array of 0. e.g

$col = array_reverse($collection);
$lastItem = $col[0];

hope this helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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