Framework: [Request] $collection->next()

Created on 2 Jun 2014  路  8Comments  路  Source: laravel/framework

Hi @taylorotwell , wouldn't it be nice if we can get a collection's "previous" and "next" items by calling $collection->next() and $collection->previous()? If it's good to be implemented, it's only natural that $collection->current() should be implemented as well.

This will be specially useful when we're referring to a collection within a loop.

Eg:

for ($i = 1; $i <= 26; $i++) {
 echo $alphabet->previous();
 echo $alphabet->current();
 echo $alphabet->next();
 echo ':D';
}

This would print following

a
b
:D
a
b
c
:D
b
c
d
:D
...
...
...

Whaddyathink?

Most helpful comment

You have to get the Iterator first:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);

All 8 comments

Aren't those already in there, since we implement Iterable ?

@Anahkiasen : We can iterate through a collection, but if you take a look at the example I have given, you can see that it's not the collection that's been iterated here. What I need is getting the next and previous of a collection, when we are referring to it within a loop based on something else (May be iterating through another collection, or a for loop like above.).

I don't know if that make sense. :)

There is already a $collection->random() method implemented. I think that is another reason to implement the requested methods.

Hmm, no plans to put this in core right now. You can extend collection to add your own methods if you wish.

:+1:

You have to get the Iterator first:

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);

Call to undefined method App\Model::getIterator()

on collection item:

          $collection = $item->getIterator();

$current = current($collection);
$next = next($collection);

        @endphp

{{$next->id}}

        @php
          if($loop->last != $loop->index){
            $next = $items->get(--$loop->index)->amount;
          }else{
            $next = null;
          }

          $runningBalance = $balance = $balance - $next;
        @endphp
Was this page helpful?
0 / 5 - 0 ratings

Related issues

fideloper picture fideloper  路  3Comments

JamborJan picture JamborJan  路  3Comments

felixsanz picture felixsanz  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments