How to count laravel collection items. what is use of collection countBy() method. In this tutorial we will discuss laravel collection count() and countBy() method. collection count in laravel 8, laravel 9, laravel 10.
Laravel collection count
laravel collection count() method return total number of items in given collection. you can also use count method to multilevel collections. see below example
$collection = collect([1, 2, 3, 4, 5]); $collection->count(); // 5
Laravel collection countBy() method
laravel collection countBy() method count occurance of every element. when you want to count how many times a value occure in a collection use countBy method. see below example
$collection = collect(['red', 'black', 'red', 'white']); $counted = $collection->countBy(); dd($counted); // ['red' => 2, 'black' => 1, 'white' => 1]
Use function in collection countBy
You can also use a function in collection countBy method
$collection = collect([ ["name"=>"Anmol", "age"=>"24"], ["name"=>"Alok", "age"=>"26"], ["name"=>"Krishan", "age"=>"24"], ]); $countByAge = $collection->countBy(function ($item) { return $item['age']; }); dd($countByAge); //['24' => 2, '26' => 1]