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

25-Apr-2023

.

Admin

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

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

]

}

I hope it can help you...

#Laravel 10