Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference next item in a Laravel collection

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

like image 372
samiles Avatar asked Jan 31 '16 12:01

samiles


2 Answers

You have to get the Iterator first:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);
like image 151
shrimpwagon Avatar answered Nov 09 '22 00:11

shrimpwagon


The collection will be keyed by an incrementing index so you should be able to do...

$collection = $statushistory->where('itemid', $timelineitemid);

foreach ($collection->values() as $index=>$hist){
      //stuff here
      $next =$collection->get(++$index) ;  
 } 

Blade syntax obviously a bit different but hopefully illustrate the idea

like image 26
Mike Miller Avatar answered Nov 08 '22 23:11

Mike Miller