Laravel Collection count and countBy Method Example

  358 views   5 months ago Laravel

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.

count() method

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

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.

Author : Harsukh Makwana
Harsukh Makwana

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]