Ad

Remove Last Two Rows In A Laravel Collection Object

- 1 answer

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

Ad

Answer

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);
Ad
source: stackoverflow.com
Ad