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']