AppDividend
Latest Code Tutorials

Laravel Collections Tutorial With Example | Laravel 5.8 Guide

0

Laravel Collections Tutorial With Example is today’s topic. The Illuminate\Support\Collection class provides a convenient wrapper for working with PHP arrays of data. Laravel Collection class allows us to chain its methods to perform fluent mapping and reducing of the underlying array. In general, Laravel collections are immutable, meaning every Collection method returns an entirely new Collection instance.

Laravel Collections Tutorial

Laravel collections are an API wrapper for PHP array functions. But it has much more features than PHP array processing. We can also create a collection from an array.

Creating Collections in Laravel

The collect helper returns the new Illuminate\Support\Collection instance for the given array.

See the following simple example. If you have installed fresh laravel, then write the following code inside the routes >> web.php file.

<?php

// web.php

Route::get('/', function () {
    $arr = [19, 21, 46];
    $collection = collect($arr);
    dd($collection);
});

Now, start the Laravel development server using the following command.

php artisan serve

Go to this URL: http://localhost:8000 and see the output.

 

Laravel Collections Tutorial With Example | Laravel 5.8 Guide

So, we have successfully created collections from the PHP array.

Extending Collections

Collections are macroable, which means that it allows us to add additional methods to the Collection class at run time.

Let’s see the following example. So write the following code inside the routes >> web.php file.

<?php

// web.php

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Route::get('/', function () {
    Collection::macro('ucFirst', function () {
        return $this->map(function ($value) {
            return Str::ucfirst($value);
        });
    });
    $collection = collect(['krunal', 'lathiya']);
    $result = $collection->ucFirst();
    dd($result);
});

So, here first, we have imported two namespaces for Collection and Str. Then we have used the macro method of Collection class and map every element of the collection and convert into ucfirst convention means the string’s first character will be converted to Capital Letter.

See the output below.

 

Extending Collections in Laravel

trait Macroable

In the above example, we have used the Macroable trait which has the following syntax.

static macro(string $name, object|callable $macro)

So, the first argument is a string and the second argument is callable macro or object, in our case, it is a collection of items which then iterate through the map function.

You can find more about Collection on this link.

Laravel Collection Methods

There are so many methods available for collections in Laravel. You can find it here. We will see one or two methods in this tutorial.

Laravel avg() method

The avg method returns an average value of the given key if the key is provided otherwise gives an avg of the values. See the following example.

Related Posts
1 of 43
<?php

// web.php

Route::get('/', function () {
    $result = collect([19, 21, 18, 46])->avg();
    dd($result);
});

We will get 26 as an output.

Laravel count() method

The count() method returns a total number of items in the collection.

<?php

// web.php

Route::get('/', function () {
    $result = collect([19, 21, 18, 46])->count();
    dd($result);
});

Go to the browser and refresh the root route and you will see the in the output.

There are so many methods available for collections in Laravel. Laravel collections are one of the most powerful provisions. They are what PHP arrays should be, but better.

Finally, Laravel Collections Tutorial With Example | Laravel 5.8 Guide is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.