How to access the nth object from Laravel collection object ?

Updated at 12-Jan-2022, By samar

How to access the nth object from Laravel collection object ?

Hello everyone, in this post we will look at how to solve "How to access the nth object from Laravel collection object ?" in programming.

You can access the nth object in the Laravel collection. There are lots of methods available in Laravel to get the specific item which exists at a particular number in the Laravel collection. You can use square-bracket notation to object or offsetGet() method to get a specific record from a collection object.
  • Get the nth number of item from the collection object in Laravel using square-bracket notation

    //Syntax:
    $collection[$nth]
    
    //Laravel 8 Example Code:
    $users = App\Models\User::get();
    $user = $users[0];
    
    //Or you can use it in a single line
    $user = App\Models\User::get()[0];
    <p> </p>
    
  • Get the nth number of item from collection object using offsetGet() method in Laravel

    $users = App\Models\User::get();
    $user = $users->offsetGet(1);
    
    //Or you can use it in a single line
    $user = App\Models\User::get()->offsetGet(1);
    

Back to code snippet queries related laravel