Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last two rows in a Laravel Collection Object

Tags:

php

laravel

I am trying to remove the last two row in a Laravel Collection. The size of the Collection can vary, but I will always want to remove the last two. I managed it by doing this, but out of curiosity, do you think there is a better way to do this ?

Here is my way :

$results = $results->reverse()->slice(2)->reverse();

Thanks a lot

John

like image 621
JohnWolf Avatar asked Dec 29 '15 14:12

JohnWolf


2 Answers

The Collection object's slice() method works similarly to array_slice(), allowing a negative value for the length argument, so you should be able to keep it simple and just do

$results = $results->slice(0, -2);
like image 176
Mark Baker Avatar answered Nov 15 '22 21:11

Mark Baker


You can use the pop method twice.

like image 34
Luis Montoya Avatar answered Nov 15 '22 21:11

Luis Montoya