In this tutorial we will see laravel collection key method.
Laravel collection key method
The `key` method in Laravel collection returns the key of the first item in the collection that passes a given truth test. If no item passes the test, the method returns null.
The syntax of the `key` method is:
$collection->key($callback);
Here, `$collection` is the instance of the Laravel collection, and `$callback` is an optional closure or string used to test each item in the collection. If `$callback` is not provided, the `key` method returns the key of the first item in the collection.
Example Usage:
Let's say we have a collection of students, and we want to find the key of the first student whose name starts with the letter 'J'. We can use the `key` method as follows:
$students = collect([
['name' => 'John', 'age' => 21],
['name' => 'Jane', 'age' => 22],
['name' => 'Jim', 'age' => 23],
['name' => 'Jake', 'age' => 24],
]);
$key = $students->key(function ($student, $key) {
return substr($student['name'], 0, 1) === 'J';
});
echo $key; // Output: 0
In the above example, the `key` method returns the key 0, which is the index of the first student in the collection whose name starts with the letter 'J' (i.e., 'John').