Reference next item in a Laravel collection
Asked Answered
B

2

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

Borchert answered 31/1, 2016 at 12:55 Comment(0)
K
7

You have to get the Iterator first:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);
Khz answered 30/5, 2017 at 15:38 Comment(0)
O
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

Orvie answered 31/1, 2016 at 13:37 Comment(2)
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.Erichericha
@Erichericha These don't seem to be working. The $next var is always null. Any ideas...?Borchert

© 2022 - 2024 — McMap. All rights reserved.