Laravel Collection first() and firstWhere() Methods Example

Laravel Collection first() and firstWhere() Methods Example

In this post we will give you information about Laravel Collection first() and firstWhere() Methods Example. Hear we will give you detail about Laravel Collection first() and firstWhere() Methods ExampleAnd how to use it also give you demo for it if it is necessary.

Hi Dev,

If you need to see example of laravel collection first example. let’s discuss about laravel collection first where example. you will learn how to get first element from collection in laravel. i would like to share with you laravel collection first element.

I will give you some examples of how to get first element from collection in laravel. you can easily add array in laravel 5, laravel 6 and laravel 7.

Let’s see example:

Example 1: Laravel Collection First Example

public function index()

{

$collection = collect([

['id'=>1, 'name'=>'Hardik'],

['id'=>2, 'name'=>'Vimal'],

['id'=>3, 'name'=>'Harshad'],

['id'=>4, 'name'=>'Harsukh'],

]);

$first = $collection->first();

dd($first);

}

Output:

Array

(

[id] => 1

[name] => Hardik

)

Example 2: Laravel Collection First Where Example

public function index()

{

$collection = collect([

['id'=>1, 'name'=>'Hardik', 'salery' => '15000'],

['id'=>2, 'name'=>'Vimal', 'salery' => '10000'],

['id'=>3, 'name'=>'Harshad', 'salery' => '17000'],

['id'=>4, 'name'=>'Harsukh', 'salery' => '18000'],

]);

$first = $collection->firstWhere('name', 'Hardik');

dd($first);

}

Output:

Array

(

[id] => 1

[name] => Hardik

[salery] => 15000

)

Example 3: Laravel Collection First Where with Operator Example

public function index()

{

$collection = collect([

['id'=>1, 'name'=>'Hardik', 'salery' => 15000],

['id'=>2, 'name'=>'Vimal', 'salery' => 10000],

['id'=>3, 'name'=>'Harshad', 'salery' => 17000],

['id'=>4, 'name'=>'Harsukh', 'salery' => 18000],

]);

$first = $collection->firstWhere('salery', '>', 16000);

dd($first);

}

Output:

Also see:Laravel Collection contains() and containsStrict() Methods Example

Array

(

[id] => 3

[name] => Harshad

[salery] => 17000

)

I hope it can help you…

Hope this code and post will helped you for implement Laravel Collection first() and firstWhere() Methods Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

77  +    =  85

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US