Friday, September 5, 2025
HomeLanguagesLaravel 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

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

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS