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


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

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

How to Send SMS using Twilio in Laravel

Twilio shares cloud communications trends, customer tales, and advice for using Twilio's APIs to build scalable voice and SMS applications.

Laravel whereBetween Query Example

In this post, we will see Laravel whereBetween query model. SQL gives numerous different sorts of techniques or queries to get separated information f...

Laravel – Where Condition with Two Columns Example

laravel where with two column example, two column where laravel , table column condition in laravel , laravel where column equals column example

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 whereMonth and whereYear Example

laravel whereMonth and whereYear example, whereMonth, whereYear, where condition in laravel 8, date function in laravel 8, whereMonth and whereYear in...