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

10-Apr-2023

.

Admin

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

Hi Friends,

I am going to explain you example of laravel 9 collection count() and countby() methods. Inside this article we will see the use of count() and countBy() methods in laravel 9 collections. Article contains a very classified information about the basic concept of Laravel 9 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:

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

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 9