In this tutorial you will learn about the Laravel Eloquent firstWhere() Example and its application with practical example.
In this Laravel Eloquent firstWhere() Example tutorial I will show you how to use Eloquent firstWhere() method in laravel. In this tutorial you will learn about the use case and how to use Eloquent firstWhere() method in laravel model query. In this article I will share various example to use Eloquent firstWhere() method in laravel application.
What Is Eloquent firstWhere() method?
The eloquent firstWhere() method returns the first element in the collection with the given key / value pair. In laravel eloquent firstWhere() method will help you to easily fetch match first record.
Laravel Eloquent firstWhere() Example
The FirstWhere method returns the first element in the collection with the given key / value pair.
Example 1:
1 2 3 4 5 6 7 8 |
$collection = collect([ ['name' => 'Regena', 'age' => null], ['name' => 'Linda', 'age' => 14], ['name' => 'Diego', 'age' => 23], ['name' => 'Linda', 'age' => 84], ]); $collection->firstWhere('name', 'Linda'); |
Output
1 |
// ['name' => 'Linda', 'age' => 14] |
Example 2:
1 2 3 4 5 6 7 8 |
$collection = collect([ ['name' => 'Regena', 'age' => null], ['name' => 'Linda', 'age' => 14], ['name' => 'Diego', 'age' => 23], ['name' => 'Linda', 'age' => 84], ]); $collection->firstWhere('age', '>=', 18); |
Output
1 |
['name' => 'Diego', 'age' => 23], |
Example 3:
1 2 3 4 5 6 7 8 |
$collection = collect([ ['name' => 'Regena', 'age' => null], ['name' => 'Linda', 'age' => 14], ['name' => 'Diego', 'age' => 23], ['name' => 'Linda', 'age' => 84], ]); $collection->firstWhere('age'); |
Output:
1 |
// ['name' => 'Linda', 'age' => 14] |