Skip to content

All topics  /  Laravel

Laravel 10 Collection count() and countBy() Methods Example

Laravel ·

Teams applying “Laravel 10 Collection count() and countBy() Methods Example” in a production project can use cybervetting to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

Hi Friends,

I am going to explain to you an example of laravel 10 collection count() and countby() methods. In this article we will see the use of count() and countBy() methods in laravel 10 collections. The article contains a piece of very classified information about the basic concept of Laravel 10 Collection count() and countBy().

We will see the concept of counting the number of items in laravel collection. We will count all items in a collection and also will cover count element-wise.

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We’ll use the collect helper to create a new collection instance from the array.

Let's see bellow example:

Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app

Add Controller

php artisan make:controller SiteController

Example 1: Use count() Method

app/Http/Controllers/SiteController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $data = collect([1, 2, 3, 4, 2, 3, 1, 5, 4, 7, 6, 8, 9, 3, 10]);
        $total = $data->count();
        echo "Total Collection Items: " . $total;
    }
}

Output:

Total Collection Items : 15

Example 2: Use countBy() Method

app/Http/Controllers/SiteController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $data = collect([1, 2, 3, 4, 2, 3, 1, 5, 4, 7, 6, 8, 9, 3, 10, 4, 5]);
        $elements = $data->countBy();
        dd($elements);
    }
}

Output:

Illuminate\Support\Collection{
    items: array:10[
        1=>2
        2=>2
        3=>3
        4=>3
        5=>2
        7=>1
        6=>1
        8=>1
        9=>1
        10=>1
    ]
}