Link to the next item in the Laravel collection

I am viewing a Laravel collection sorted by created_at to create a timeline. The start date for each created_at element, and the end date is created_at next element. If this is the last item, the event lasts only 30 days.

My current code is:

 @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 the start date, but I need it to be the start date of the next item. I thought there would be an assistant for collectors like last() , which I could just call next() or whatever. Since there is no numeric key, I cannot just add it and grab it. The item is sorted by date, and the only identifier field is the name from the database, which is a random identifier, such as 1434 or 1356.

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

Thank you very much

+6
source share
2 answers

The fee will be determined by index with index so you can ...

 $collection = $statushistory->where('itemid', $timelineitemid); foreach ($collection->values() as $index=>$hist){ //stuff here $next =$collection->get(++$index) ; } 

Blade's syntax is obviously a bit different, but hopefully illustrates the idea

+2
source

First you should get an Iterator:

 $collection = $collection->getIterator(); $current = current($collection); $next = next($collection); 
+2
source

All Articles