How to access the nth object in a Laravel collection object?

theHands picture theHands · Jun 26, 2014 · Viewed 24.2k times · Source

I have a laravel collection object.

I want to use the nth model within it.

How do I access it?

Edit:

I cannot find a suitable method in the laravel documentation. I could iterate the collection in a foreach loop and break when the nth item is found:

foreach($collection as $key => $object)
{
    if($key == $nth) {break;}
}
// $object is now the nth one

But this seems messy.

A cleaner way would be to perform the above loop once and create a simple array containing all the objects in the collection. But this seems like unnecessary duplication.

In the laravel collection class documentation, there is a fetch method but I think this fetches an object from the collection matching a primary key, rather than the nth one in the collection.

Answer

Phil picture Phil · Jun 27, 2014

Seeing as Illuminate\Support\Collection implements ArrayAccess, you should be able to simply use square-bracket notation, ie

$collection[$nth]

This calls offsetGet internally which you can also use

$collection->offsetGet($nth)

and finally, you can use the get method which allows for an optional default value

$collection->get($nth)
// or
$collection->get($nth, 'some default value')