To count the total number of items in a Laravel collection, you can use the count
method. This method will return the number of items in the collection.
Here’s an example:
$collection = collect([1, 2, 3, 4, 5]);
$count = $collection->count();
// $count is now 5
You can also use the size
method, which is an alias of the count
method:
$collection = collect([1, 2, 3, 4, 5]);
$count = $collection->size();
// $count is now 5
If you want to count the number of items in a specific key of the collection items, you can pass the key to the count
method:
$collection = collect([
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30],
['name' => 'Charlie', 'age' => 35],
]);
$count = $collection->count('age');
// $count is now 3
Note that the count
method will only count the items in the collection, not the sum of the values of a specific key. If you want to calculate the sum of the values of a specific key, you can use the sum
method.
$collection = collect([
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30],
['name' => 'Charlie', 'age' => 35],
]);
$sum = $collection->sum('age');
// $sum is now 90