Search

Laravel Collection count and countBy Method Example

post-title

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' => 'johndoe@gmail.com']);

$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.