Reference next item in a Laravel collection

samiles picture samiles · Jan 31, 2016 · Viewed 10.3k times · Source

I am looping through a Laravel collection sorted by created_at to make a timeline. The start date for each item is created_at, and the end date is the created_at of the following item. If it is the last item, the event just lasts for a set 30 days.

My current code is this:

@foreach ($statushistory->where('itemid', $timelineitemid) as $hist)
    [ '{{$hist->newstatus}}', new Date({{$hist->created_at->format('Y')}}, {{$hist->created_at->format('n')-1}}, {{$hist->created_at->format('j')}}), new Date({{$hist->created_at->format('Y')}}, {{$hist->created_at->format('n')-1}}, {{$hist->created_at->format('j')}}) ],
@endforeach

As you can see here the end date is just the same as the start date, but I need it to be the start date of the next item. I thought there would be a helper like last() for collections that I could just call next() or whatever. As there's no numeric key, I can't just add one and grab it. The item are sorted by date, and the only ID type field is the one from the database which is a random ID like 1434 or 1356.

Any ideas on how to get the next item's start_date, and check if we are at the last item? I looked at PHP's next function but I don't think it does what I need.

Many thanks

Answer

shrimpwagon picture shrimpwagon · May 30, 2017

You have to get the Iterator first:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);