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

前端 未结 3 639
予麋鹿
予麋鹿 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:29

    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')
    

提交回复
热议问题