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

前端 未结 3 611
予麋鹿
予麋鹿 2021-01-01 12:38

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 l

3条回答
  •  有刺的猬
    2021-01-01 13:18

    @Phil's answer doesn't quite obtain the nth element, since the keys may be unordered. If you've got an eloquent collection from a db query it'll work fine, but if your keys aren't sequential then you'll need to do something different.

    $collection = collect([0 => 'bish', 2 => 'bash']); $collection[1] // Undefined index

    Instead we can do $collection->values()[1] // string(4) bash which uses array_values()

    Or even make a macro to do this:

    Collection::macro('nthElement', function($offset, $default = null) {
        return $this->values()->get($offset, $default);
    }):
    

    Example macro usage:

    $collection = collect([0 => 'bish', 2 => 'bash']);
    $collection->nthElement(1) // string(4) 'bash'
    $collection->nthElement(3) // undefined index
    $collection->nthElement(3, 'bosh') // string (4) bosh
    

提交回复
热议问题