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
get
after thewhere
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 theforeach
should iterate$collection->values()
to make sure the$index
values are actually sequential. – Erichericha