Laravel Eloquent firstWhere() Example

Laravel Eloquent firstWhere() Example

Laravel eloquent firstWhere() example. In this tutorial, you will learn about laravel eloquent firstWhere() method with examples.

And this tutorial will help you simply about how to use laravel eloquent firstwhere().

Note that, The firstWhere method returns the first element in the collection with the given key / value pair.

Sometimes, you need to fetch data from id then you can easily fetch from find() method, but when you need to fetch data from category, age, name then you have to use first() method. But laravel eloquent provide firstWhere() method that will help you to easily fetch match first record.

Laravel Eloquent firstWhere() Examples

The FirstWhere method returns the first element in the collection with the given key / value pair.

Example 1:

$collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('name', 'Linda');

Output:

// ['name' => 'Linda', 'age' => 14]

Example 2:

$collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('age', '>=', 18);

Output:

    ['name' => 'Diego', 'age' => 23],

Example 3:

$collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('age');

Output:

// ['name' => 'Linda', 'age' => 14]

Recommended Laravel Posts

Recommended:-Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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