How to Use Collection count() and countBy() Methods in Laravel 8?


Share:
 | Published By: Admin | Published On: Jan 29, 2022 | Category: Laravel 8

Hi Friends,

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

We will see the concept of count number of items in laravel collection. We will count all items in a collection 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:

Step 1: Download Laravel

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

composer create-project laravel/laravel example-app
Step : 2 - Create Controller
php artisan make:controller CollectController
Example #1 Use count() Method

/app/Http/Controllers
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    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
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    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
    ]
}
I hope it can help you...
Share: