Collections In Laravel

Introduction

We can think Collection as Objects of objects. It works as a wrapper over an array by providing some more methods. As every item in Collection have some objects, It will be able to give some extra features like (Paging results, Checking for odd or even, ->isOdd(), etc.)

In general a collection can be referred as a set that can contain any can kind of data object like (Array, ArrayList(In java), LinkedList, Vector, Stack, Queue, etc.)

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, run the strtoupper function on each element, and then remove all empty elements:

$collection = collect(['taylor', 'abigail', 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(means to say unchangeable in nature), and every Collection method(applied in chaining) returns an entirely new Collection instance.

e.g. We can look something like.

Collection2 = Collection1->methodOne(); // will return a new collection named Collection2
Collection3 = Collection2->methodTwo(); // will return a new Collection named Collection3

Above two lines are equivalent to a single line as below,

Collection3 = Collection1->methodOne()->methodTwo();

Collection class is able to provide many methods few of them are –

all, average, avg , chunk, collapse, combine, contains, containsStrict, count, diff, diffAssoc, diffKeys, each, every,except.

Examples


collect([1, 2, 3])->all();

// [1, 2, 3]

$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20

$average = collect([1, 1, 2, 4])->avg();

// 2

Leave a Reply

Your email address will not be published. Required fields are marked *