What Is Collections In Laravel Framework With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data.

What Is Collections In Laravel Framework With Example

Collections

For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:

$collection = collect(['shiva', 'kumar', null])->map(function ($name) {
    return strtoupper($name);
})
->reject(function ($name) {
    return empty($name);
});
 

As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.

Creating Collections

As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:
 

$collection = collect([1, 2, 3]);

The results of Eloquent queries are always returned as Collection instances.

Extending Collections

Collections are "macroable", which allows you to add additional methods to the Collection class at run time. For example, the following code adds a toUpper method to the Collection class:

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

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
         return Str::upper($value);
    });
});

$collection = collect(['shiva', 'kumar']);

$upper = $collection->toUpper();

// ['SHIVA', 'KUMAR']

 

Related Post