How to access the nth item in a Laravel collection? How to access the nth item in a Laravel collection? laravel laravel

How to access the nth item in a Laravel collection?


I guess faster and more memory-efficient way is to use slice() method:

$collection->slice($n, 1);


You can try it using values() function as:

$collection->values()->get($n);


Based on Alexey's answer, you can create a macro in AppServiceProvider (add it inside register method):

use Illuminate\Support\Collection;Collection::macro('getNth', function ($n) {   return $this->slice($n, 1)->first();});

and then, you can use this throughout your application:

$collection = ['apple', 'orange'];$collection->getNth(0) // returns 'apple'$collection->getNth(1) // returns 'orange'$collection->getNth(2) // returns null$collection->getNth(3) // returns null