To get the first element of a Laravel collection, you can use the first
method. This method will return the first element of the collection, or null
if the collection is empty.
Here’s an example:
$collection = collect([1, 2, 3, 4, 5]);
$first = $collection->first();
// $first is now 1
You can also pass a callback to the first
method to get the first element that matches a certain condition:
$collection = collect([1, 2, 3, 4, 5]);
$first = $collection->first(function ($value, $key) {
return $value > 3;
});
// $first is now 4
If you want to get the first element and remove it from the collection, you can use the shift
method:
$collection = collect([1, 2, 3, 4, 5]);
$first = $collection->shift();
// $first is now 1
// $collection is now [2, 3, 4, 5]
Note that the first
and shift
methods return only the value of the element, not the key. If you want to get the key as well, you can use the first
method in combination with the keys
and values
methods:
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$first = $collection->first(function ($value, $key) {
return $value > 1;
});
$key = $collection->keys()->first(function ($value, $key) use ($first) {
return $collection[$key] == $first;
});
// $first is now 2
// $key is now 'b'