Table of contents

laravel collection

In this example, I will show you how to implement the Laravel 8, and 9 Collection with first() and firstWhere() methods. When doing a Laravel project we should use Laravel collection for easier to process our array data. We will use the collect helper function of Laravel to create a new collection instance from our array.

 

And sometimes you need to get the first element or with a condition query that will display the first result of our Laravel collection. With the use of first() and firstWhere() methods will make it easier for us.

 

Example 1: Laravel Collection first() Method Example

See below code example on how to implement Laravel collection.

 

public function index()
{
    $collection = collect([
        ['id'=>	1, 'name'=>'Juan Dela Cruz', 'age' => 25],
        ['id'=>	2, 'name'=>'Juana Vasquez', 'age' => 31],
        ['id'=>	3, 'name'=>'Jason Reyes', 'age' => 27],
        ['id'=>	4, 'name'=>'Jake Ramos', 'age' => 43],
    ]);
  
    $first = $collection->first();
  
    dd($first);
}

 

Output:

array:3 [â–¼
  "id" => 1
  "name" => "Juan Dela Cruz"
  "age" => 25
]

 

Example 2: Laravel Collection first() Method Example

public function index()
{
    $collection = collect([
        ['id'=>	1, 'name'=>'Juan Dela Cruz', 'age' => 25, 'gender' => 'Male'],
        ['id'=>	2, 'name'=>'Juana Vasquez', 'age' => 31, 'gender' => 'Female'],
        ['id'=>	3, 'name'=>'Jason Reyes', 'age' => 27, 'gender' => 'Male'],
        ['id'=>	4, 'name'=>'Jake Ramos', 'age' => 43, 'gender' => 'Male'],
    ]);
  
    $first = $collection->firstWhere('name', 'Juan Dela Cruz');
  
    dd($first);
}

 

Output:

laravel collection

 

That's it I hope you learn how to get the first element of the Laravel collection using first() and firstWhere() methods.

 

Thank you for reading :)