The database query builder in Laravel provides a simple, intuitive interface for generating and performing database queries. It works with every one of Laravel's supported database systems and may be used to conduct most operations on the database in your application.

In this example, I'll teach you how to use the first() and firstWhere() methods to construct the Laravel 8 Collection. When working on a Laravel project, we should make use of Laravel collection to make processing array data easier. To generate a new collection instance from our array, we'll utilise Laravel's collect helper function.
And there are occasions when you need to get the first element or use a condition query to display the first Laravel collection result. It will be easier for us if we use the first() and firstWhere() methods.

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);
}

 

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);
}

I hope you will like the content and it will help you to learn Laravel 8 Collection with first() and firstWhere() Methods Example
If you like this content, do share.


Recommended Posts

View All

Laravel One to One Eloquent Relationship Tutorial


Laravel One To One Eloquent Relationships Tutorial Example, Laravel Eloquent ORM is the best possible database solution, ORM Mapping is very easy, lar...

Laravel Has Many Through Eloquent Relationship


Laravel has many through pivot table, Laravel has many through relationship example, has_many through relationship Laravel, hasmanythrough laravel inv...

Laravel Query Builder Where Exists Example


laravel use sql where exists clause,laravel whereExists, laravel whereExists not working,laravel where exists example,laravel exists query

Laravel 9 GEO Chart Example using LavaCharts


Learn how to create interactive GEO charts with Laravel 9 and LavaCharts. Visualize your data on maps and improve data analysis. Check it out now!

Google Map with Multiple Marker and Info Box in Laravel


This tutorial will teach you how to use Laravel to integrate a Google Map with numerous markers and an info box.