Laravel Eloquent firstWhere() Example

Laravel Eloquent firstWhere() Example

Sometimes, you need to fetch data using id, you can use 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.

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

Eloquent firstWhere() in laravel. In this tutorial, you will learn about laravel eloquent firstWhere() method with multiple conditions examples.

Laravel Eloquent firstWhere() Examples

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

Example 1: Basic Usage

Retrieve the first user with a specific name:

$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: Advance Usage

Get the first user with a age greater than and equal to 18:

$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]

Example 4: Dynamic Conditions

Conditions can be dynamically set based on user input or other factors.

$column = 'dynamic_column';
$value = 'dynamic_value';

$record = YourModelName::firstWhere($column, $value);

Recommended Laravel Posts

Recommended:-Laravel Try Catch

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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