3

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(); 
$i=0;
foreach($collections as $collection){
  if($i == 0){
    $firstItem = $collection;
    $i++;
  } else{
    $lastItem = $collection;
  }
}
1
  • 2
    $lastItem = $collections->getLastItem(); and $firstItem = $collections->getFirstItem(); is not working? – Amit Bera Mar 13 '17 at 3:52
3

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.

3

This is Tested Solution feel free to implement

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

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

print_r($firstItem->getData());

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

print_r($lastItem->getData());

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.