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, 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]);
Note
The results of Eloquent queries are always returned as
Collectioninstances.
Available Methods
For the remainder of this documentation, we'll discuss each method available on the Collection class. Remember, all of these methods may be chained to fluently manipulating the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:
all average avg chunk collapse combine contains containsStrict count diff diffAssoc diffKeys each every except filter first flatMap flatten flip forget forPage get groupBy has implode intersect intersectByKeys isEmpty isNotEmpty keyBy keys last map mapWithKeys max median merge min mode nth only partition pipe pluck pop prepend pull push put random reduce reject reverse search shift shuffle slice sort sortBy sortByDesc splice split sum take tap times toArray toJson transform union unique uniqueStrict values when where whereStrict whereIn whereInStrict whereNotIn whereNotInStrict zip
Method Listing
all()
The all method returns the underlying array represented by the collection:
collect([1, 2, 3])->all();
// [1, 2, 3]