Laravel Collections

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:
コレクションは普通の文法です。laravelにサポートされてるんですね。

$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]);

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\Str;

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

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

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 manipulate the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:
うわ、すげーある。
allaverageavgchunkcollapsecombineconcatcontainscontainsStrictcountcrossJoindddiffdiffAssocdiffKeysdumpeacheachSpreadeveryexceptfilterfirstfirstWhereflatMapflattenflipforgetforPagegetgroupByhasimplodeintersectintersectByKeysisEmptyisNotEmptykeyBykeyslastmacromakemapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergeminmodenthonlypadpartitionpipepluckpopprependpullpushputrandomreducerejectreversesearchshiftshuffleslicesortsortBysortByDescsortKeyssortKeysDescsplicesplitsumtaketaptimestoArraytoJsontransformunionuniqueuniqueStrictunlessunwrapvalueswhenwherewhereStrictwhereInwhereInStrictwhereInstanceOfwhereNotInwhereNotInStrictwrapzip

Method Listing
これ全部やる気か。プログラマーってすごいね。って、中身見ると普通だな。

collect([1, 2, 3])->all();
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
$average = collect([1, 1, 2, 4])->avg();
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
$collection->contains('New York');
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
    return $value > 5;
});
$collection = collect([1, 2, 3, 4]);
$collection->count();
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
$collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
]);
$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6
]);
$diff->all();
$collection->each(function ($item, $key) {
});
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();

Higher Order Messages
Collections also provide support for “higher order messages”, which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, sortBy, sortByDesc, sum, and unique.

Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let’s use the each higher order message to call a method on each object within a collection: