In this article, we will discuss about how you can get number of items in collection or array in Laravel collection using count() and countBy() method. This is useful in Admin Panel dashboard where you want to give overview of data.
The count method simply returns the total number of items in given array.
$data = collect([0, 1, 2, 3, 4]);
$data->count(); // 5
You can also check for associative array.
$new_data = collect(['id' => 1, 'name' => 'john', 'email' => '[email protected]']);
$new_data->count(); // 3
countBy() method is used to get number of times items used in given collection.
$data = collect([1, 2, 2, 2, 3]);
$new_data = $data->countBy();
$new_data->all();
You can also get count by custom value.
$data = collect([
["product_id" => 1, "size" => "XL"],
["product_id" => 2, "size" => "M"],
["product_id" => 3, "size" => "L"],
["product_id" => 4, "size" => "M"],
]);
$counted = $collection->countBy(function($value) {
return $value['size'];
});
$new_data->all(); // ["XL" => 1, "M" => 2, "L" => 1]
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to Create HTTP request in Node.js using node-fetch module
Node.js has many packages to make HTTP r...How to use specific private SSH key in git commands
When you run git or ssh commands, it wil...Create CRUD Application Example with REST Web API in Angular
In this article, I will share with you h...How to move an element to left, right, up and down using arrow keys in jQuery
Use the jQuery keydown() method You c...How to get a website's favicon with PHP
While working with my one of project, I...