The `Arr::first()` method is part of Laravel 11.x `Illuminate\Support\Arr` helper class. It is used to retrieve the first element of an array that passes a given truth test (callback function). If no callback is given, it simply returns the first element of the array.
Basic Usage of `Arr::first()`
use Illuminate\Support\Arr; $numbers = [10, 20, 30, 40]; $first = Arr::first($numbers); echo $first; // Output: 10
Using a Callback to Find the First Matching Element
You can pass a callback function to filter the first item that meets a condition.
use Illuminate\Support\Arr; $numbers = [10, 20, 30, 40]; $firstEven = Arr::first($numbers, function ($value) { return $value > 15; }); echo $firstEven; // Output: 20 (because it's the first value greater than 15)
Providing a Default Value if No Match is Found
If no element meets the condition, you can pass a default value.
use Illuminate\Support\Arr; $numbers = [10, 20, 30, 40]; $firstGreaterThan50 = Arr::first($numbers, function ($value) { return $value > 50; }, 'No match'); echo $firstGreaterThan50; // Output: No match
Use Case in a Laravel Controller
This can be useful when filtering data from a collection or database query results.
use Illuminate\Support\Arr; $users = [ ['name' => 'Alice', 'age' => 25], ['name' => 'Bob', 'age' => 30], ['name' => 'Charlie', 'age' => 22] ]; $firstAdult = Arr::first($users, function ($user) { return $user['age'] > 25; }); print_r($firstAdult);
Output:
Array ( [name] => Bob [age] => 30 )