8

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

samiles
  • 3,768
  • 12
  • 44
  • 71

2 Answers2

7

You have to get the Iterator first:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);
shrimpwagon
  • 867
  • 12
  • 23
4

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

Mike Miller
  • 3,071
  • 3
  • 25
  • 32
  • Correct answer, with two small observations. First, I think the `get` after the `where` method is redundant since I `$statushistory` is already a collection (otherwise it wouldn't be possible to iterate over it as shown in the question). Since the OP specified that the collection was sorted, it might have been sorted after being fetched from the database, so the array keys might be mixed up, so the `foreach` should iterate `$collection->values()` to make sure the `$index` values are actually sequential. – Bogdan Jan 31 '16 at 14:12
  • @Bogdan These don't seem to be working. The $next var is always null. Any ideas...? – samiles Jan 31 '16 at 20:16