Laravel Eloquent firstWhere() Example Tutorial

Laravel eloquent firstWhere() example; Through this tutorial, i am going to show you how to use firstWhere() eloquent in laravel apps.

Laravel Eloquent firstWhere() Example Tutorial

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

Here, i will take some example of laravel eloquent firstWhere(); is as follows:

Example 1 – Laravel Eloquent firstWhere() Example

Let’s take an first example for firstWhere() eloquent in laravel apps; is as follows:

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

The output of the above code is; as follows:

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

Example 2 – Laravel Eloquent firstWhere() Example

Let’s take an second example for firstWhere() eloquent in laravel apps; is as follows:

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

The output of the above code is; as follows:

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

Recommended Laravel Tutorials

Leave a Comment