DEV Community

Code And Deploy
Code And Deploy

Posted on • Updated on

Laravel 8 Collection with first() and firstWhere() Methods Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-collection-with-first-and-firstwhere-methods-example

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this example, I will show you how to implement the Laravel 8 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

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);
}
Enter fullscreen mode Exit fullscreen mode

Output:

array:3 [▼
  "id" => 1
  "name" => "Juan Dela Cruz"
  "age" => 25
]
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Output:

Laravel 8 Collection

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

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Thank you for reading :)

Top comments (0)