ItSolutionStuff.com

Laravel Collection first() and firstWhere() Methods Example

By Hardik Savani β€’ April 16, 2024
Laravel

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, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11.

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:

Array

(

[id] => 3

[name] => Harshad

[salery] => 17000

)

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

Laravel Collection Forget | Remove Item from Collection Laravel

Read Now β†’
β˜…

Laravel Collection Push() and Put() Example

Read Now β†’
β˜…

Laravel Collection SortByDesc Tutorial with Examples

Read Now β†’
β˜…

Laravel Collection SortBy Tutorial with Examples

Read Now β†’
β˜…

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now β†’
β˜…

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now β†’
β˜…

Laravel Collection Search Method Example

Read Now β†’
β˜…

Laravel Collection Filter Method Example

Read Now β†’