Readouble

Laravel 5.5 コレクション

イントロダクションIntroduction

Illuminate\Support\Collectionクラスは配列データを操作するための、書きやすく使いやすいラッパーです。以下の例をご覧ください。配列から新しいコレクションインスタンスを作成するためにcollectヘルパを使用し、各要素に対しstrtoupperを実行し、それから空の要素を削除しています。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);
});

ご覧の通り、Collectionクラスは裏にある配列をマップ操作してから要素削除するメソッドをチェーンでスムーズにつなげてくれます。つまり元のコレクションは不変であり、全てのCollectionメソッドは新しいCollectionインスタンスを返します。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

上記の通りcollectヘルパは指定された配列を元に、新しいIlluminate\Support\Collectionインスタンスを返します。ですからコレクションの生成も同様にシンプルです。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]);

lightbulb">Tip!! Eloquentクエリの結果は、常にCollectionインスタンスを返します。{tip} The results of Eloquent[/docs/{{version}}/eloquent] queries are always returned as Collection instances.

コレクションの拡張Extending Collections

実行時にCollectionクラスメソッドを追加できるように、コレクションは「マクロ使用可能」です。例として、CollectionクラスへtoUpperメソッドを追加してみましょう。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();

// ['FIRST', 'SECOND']

通常、サービスプロバイダの中で、コレクションマクロを定義します。Typically, you should declare collection macros in a service provider[/docs/{{version}}/providers].

利用可能なメソッドAvailable Methods

このドキュメントの残りで、Collectionクラスで使用できる各メソッドを解説します。これらのメソッドは、全て裏の配列をスラスラと操作するためにチェーンで繋げられることを覚えておきましょう。さらにほとんどのメソッドは、新しいCollectionインスタンスを返しますので、必要であればコレクションのオリジナルコピーを利用できるように変更しません。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:

メソッド一覧Method Listing

all() {#collection-method .first-collection-method}all() {#collection-method .first-collection-method}

allメソッドはコレクションの裏の配列表現を返します。The all method returns the underlying array represented by the collection:

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

// [1, 2, 3]

average() {#collection-method}average() {#collection-method}

avgメソッドのエイリアスです。Alias for the avg[#method-avg] method.

avg() {#collection-method}avg() {#collection-method}

avgメソッドは、指定したキーの平均値を返します。The avg method returns the average value[https://en.wikipedia.org/wiki/Average] of a given key:

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

// 20

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

// 2

chunk() {#collection-method}chunk() {#collection-method}

chunkメソッドはコレクションを指定したサイズで複数の小さなコレクションに分割します。The chunk method breaks the collection into multiple, smaller collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

このメソッドは特にBootstrapのようなグリッドシステムをビューで操作する場合に便利です。Eloquentモデルのコレクションがあり、グリッドで表示しようとしているところを想像してください。This method is especially useful in views[/docs/{{version}}/views] when working with a grid system such as Bootstrap[https://getbootstrap.com/css/#grid]. Imagine you have a collection of Eloquent[/docs/{{version}}/eloquent] models you want to display in a grid:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

collapse() {#collection-method}collapse() {#collection-method}

collapseメソッドは、配列のコレクションをフラットな一次コレクションに展開します。The collapse method collapses a collection of arrays into a single, flat collection:

$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

$collapsed = $collection->collapse();

$collapsed->all();

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

combine() {#collection-method}combine() {#collection-method}

combineメソッドは、キーのコレクションと、値の配列かコレクションを結合します。The combine method combines the keys of the collection with the values of another array or collection:

$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]

concat() {#collection-method}concat() {#collection-method}

concatメソッドは、指定した「配列」やコレクションの値を元のコレクションの最後に追加します。The concat method appends the given array or collection values onto the end of the collection:

$collection = collect(['John Doe']);

$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

$concatenated->all();

// ['John Doe', 'Jane Doe', 'Johnny Doe']

contains() {#collection-method}contains() {#collection-method}

containsメソッドは指定したアイテムがコレクションに含まれているかどうかを判定します。The contains method determines whether the collection contains a given item:

$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

$collection->contains('New York');

// false

さらにcontainsメソッドにはキー/値ペアを指定することもでき、コレクション中に指定したペアが存在するかを確認できます。You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', 'Bookcase');

// false

最後に、containsメソッドにはコールバックを渡すこともでき、独自のテストを行えます。Finally, you may also pass a callback to the contains method to perform your own truth test:

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

$collection->contains(function ($value, $key) {
    return $value > 5;
});

// false

containsメソッドは、アイテムを「緩く」比較します。つまり、ある整数の文字列とその整数値は等値として扱います。「厳密」な比較を行いたい場合は、containsStrictメソッドを使ってください。The contains method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the containsStrict[#method-containsstrict] method to filter using "strict" comparisons.

containsStrict() {#collection-method}containsStrict() {#collection-method}

このメソッドは、containsメソッドと使用方法は同じです。しかし、「厳密」な値の比較を行います。This method has the same signature as the contains[#method-contains] method; however, all values are compared using "strict" comparisons.

count() {#collection-method}count() {#collection-method}

countメソッドはコレクションのアイテム数を返します。The count method returns the total number of items in the collection:

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

$collection->count();

// 4

crossJoin() {#collection-method}crossJoin() {#collection-method}

crossJoinメソッドはコレクションの値と、指定した配列かコレクション間の値を交差接続し、可能性のある全順列の直積を返します。The crossJoin method cross joins the collection's values among the given arrays or collections, returning a Cartesian product with all possible permutations:

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

/*
    [
        [1, 'a', 'I'],
        [1, 'a', 'II'],
        [1, 'b', 'I'],
        [1, 'b', 'II'],
        [2, 'a', 'I'],
        [2, 'a', 'II'],
        [2, 'b', 'I'],
        [2, 'b', 'II'],
    ]
*/

dd() {#collection-method}dd() {#collection-method}

ddメソッドはコレクションアイテムをダンプし、スクリプトの実行を停止します。The dd method dumps the collection's items and ends execution of the script:

$collection = collect(['John Doe', 'Jane Doe']);

$collection->dd();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/

スクリプトの実行を止めたくない場合は、dumpメソッドを代わりに使用してください。If you do not want to stop executing the script, use the dump[#method-dump] method instead.

diff() {#collection-method}diff() {#collection-method}

diffメソッドはコレクションと、他のコレクションか一次元「配列」を値にもとづき比較します。このメソッドは指定されたコレクションに存在しない、オリジナルのコレクションの値を返します。The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection:

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

$diff = $collection->diff([2, 4, 6, 8]);

$diff->all();

// [1, 3, 5]

diffAssoc() {#collection-method}diffAssoc() {#collection-method}

diffAssocメソッドはコレクションと、他のコレクションかキー/値形式のPHP配列を比較します。このメソッドは指定したコレクションに含まれない、オリジナルコレクション中のキー/値ペアを返します。The diffAssoc method compares the collection against another collection or a plain PHP array based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
]);

$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6
]);

$diff->all();

// ['color' => 'orange', 'remain' => 6]

diffKeys() {#collection-method}diffKeys() {#collection-method}

diffKeysメソッドはコレクションと、他のコレクションか一次元「配列」をキーで比較します。このメソッドは指定したコレクションに存在しない、オリジナルコレクション中のキー/値ペアを返します。The diffKeys method compares the collection against another collection or a plain PHP array based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = collect([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
]);

$diff = $collection->diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
]);

$diff->all();

// ['one' => 10, 'three' => 30, 'five' => 50]

dump() {#collection-method}dump() {#collection-method}

dumpメソッドはコレクションアイテムをダンプします。The dump method dumps the collection's items:

$collection = collect(['John Doe', 'Jane Doe']);

$collection->dump();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/

コレクションをダンプした後にスクリプトを停止したい場合は、代わりにddメソッドを使用してください。If you want to stop executing the script after dumping the collection, use the dd[#method-dd] method instead.

each() {#collection-method}each() {#collection-method}

eachメソッドはコレクションのアイテムを繰り返しで処理し、コールバックに各アイテムを渡します。The each method iterates over the items in the collection and passes each item to a callback:

$collection = $collection->each(function ($item, $key) {
    //
});

アイテム全体への繰り返しを停止したい場合は、falseをコールバックから返してください。If you would like to stop iterating through the items, you may return false from your callback:

$collection = $collection->each(function ($item, $key) {
    if (/* 条件 */) {
        return false;
    }
});

eachSpread() {#collection-method}eachSpread() {#collection-method}

eachSpreadメソッドはコレクションのアイテムに対し、指定したコールバックへネストしたアイテム値をそれぞれ渡し、繰り返し処理します。The eachSpread method iterates over the collection's items, passing each nested item value into the given callback:

$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

$collection->eachSpread(function ($name, $age) {
    //
});

アイテムに対する繰り返しを停止したい場合は、コールバックからfalseを返します。You may stop iterating through the items by returning false from the callback:

$collection->eachSpread(function ($name, $age) {
    return false;
});

every() {#collection-method}every() {#collection-method}

everyメソッドは、コレクションの全要素が、指定したテストをパスするか判定するために使用します。The every method may be used to verify that all elements of a collection pass a given truth test:

collect([1, 2, 3, 4])->every(function ($value, $key) {
    return $value > 2;
});

// false

except() {#collection-method}except() {#collection-method}

exceptメソッドは、キーにより指定したアイテム以外の全コレクション要素を返します。The except method returns all items in the collection except for those with the specified keys:

$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);

$filtered = $collection->except(['price', 'discount']);

$filtered->all();

// ['product_id' => 1]

exceptの正反対の機能は、onlyメソッドです。For the inverse of except, see the only[#method-only] method.

filter() {#collection-method}filter() {#collection-method}

filterメソッドは指定したコールバックでコレクションをフィルタリングします。テストでtrueを返したアイテムだけが残ります。The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

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

$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [3, 4]

コールバックを指定しない場合、コレクションの全エンティティの中で、falseとして評価されるものを削除します。If no callback is supplied, all entries of the collection that are equivalent to false will be removed:

$collection = collect([1, 2, 3, null, false, '', 0, []]);

$collection->filter()->all();

// [1, 2, 3]

filterの逆の動作は、rejectメソッドを見てください。For the inverse of filter, see the reject[#method-reject] method.

first() {#collection-method}first() {#collection-method}

firstメソッドは指定された真偽テストをパスしたコレクションの最初の要素を返します。The first method returns the first element in the collection that passes a given truth test:

collect([1, 2, 3, 4])->first(function ($value, $key) {
    return $value > 2;
});

// 3

firstメソッドに引数を付けなければ、コレクションの最初の要素を取得できます。コレクションが空ならnullが返ります。You may also call the first method with no arguments to get the first element in the collection. If the collection is empty, null is returned:

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

// 1

firstWhere() {#collection-method}firstWhere() {#collection-method}

firstWhereメソッドはコレクションの中から、最初の指定したキー/値ペアの要素を返します。The firstWhere method returns the first element in the collection with the given key / value pair:

$collection = collect([
    ['name' => 'Regena', 'age' => 12],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('name', 'Linda');

// ['name' => 'Linda', 'age' => 14]

比較演算子を指定し、firstWhereメソッドを呼び出すこともできます。You may also call the firstWhere method with an operator:

$collection->firstWhere('age', '>=', 18);

// ['name' => 'Diego', 'age' => 23]

flatMap() {#collection-method}flatMap() {#collection-method}

flatMapメソッドはそれぞれの値をコールバックへ渡しながら、コレクション全体を繰り返し処理します。コールバックでは自由にアイテムの値を変更し、それを返します。その値へ更新した新しいコレクションを作成します。配列は一次元になります。The flatMap method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by a level:

$collection = collect([
    ['name' => 'Sally'],
    ['school' => 'Arkansas'],
    ['age' => 28]
]);

$flattened = $collection->flatMap(function ($values) {
    return array_map('strtoupper', $values);
});

$flattened->all();

// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

flatten() {#collection-method}flatten() {#collection-method}

flattenメソッドは多次元コレクションを一次元化します。The flatten method flattens a multi-dimensional collection into a single dimension:

$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

$flattened = $collection->flatten();

$flattened->all();

// ['taylor', 'php', 'javascript'];

このメソッドでは、いくつ配列の次元を減らすかを引数で指定できます。You may optionally pass the function a "depth" argument:

$collection = collect([
    'Apple' => [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ],
    'Samsung' => [
        ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    ],
]);

$products = $collection->flatten(1);

$products->values()->all();

/*
    [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
        ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
    ]
*/

上記の例で、flattenを次元の指定なしで呼び出すと、ネスト配列をフラットにしますので、結果は['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']になります。次元を指定すると、配列のネストをそのレベルに制約し、減らします。In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.

flip() {#collection-method}flip() {#collection-method}

flipメソッドはコレクションのキーと対応する値を入れ替えます。The flip method swaps the collection's keys with their corresponding values:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$flipped = $collection->flip();

$flipped->all();

// ['taylor' => 'name', 'laravel' => 'framework']

forget() {#collection-method}forget() {#collection-method}

forgetメソッドはキーによりコレクションのアイテムを削除します。The forget method removes an item from the collection by its key:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$collection->forget('name');

$collection->all();

// ['framework' => 'laravel']

Note: note 他のコレクションメソッドとは異なり、forgetは更新された新しいコレクションを返しません。呼び出しもとのコレクションを更新します。{note} Unlike most other collection methods, forget does not return a new modified collection; it modifies the collection it is called on.

forPage() {#collection-method}forPage() {#collection-method}

forPageメソッドは指定されたページ番号を表すアイテムで構成された新しいコレクションを返します。このメソッドは最初の引数にページ番号、2つ目の引数としてページあたりのアイテム数を受け取ります。The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

// [4, 5, 6]

get() {#collection-method}get() {#collection-method}

getメソッドは指定されたキーのアイテムを返します。キーが存在していない場合はnullを返します。The get method returns the item at a given key. If the key does not exist, null is returned:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('name');

// taylor

オプションとして第2引数にデフォルト値を指定することもできます。You may optionally pass a default value as the second argument:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('foo', 'default-value');

// default-value

デフォルト値にコールバックを渡すこともできます。指定したキーが存在していなかった場合、コールバックの結果が返されます。You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:

$collection->get('email', function () {
    return 'default-value';
});

// default-value

groupBy() {#collection-method}groupBy() {#collection-method}

groupByメソッドは指定したキーによりコレクションのアイテムをグループにまとめます。The groupBy method groups the collection's items by a given key:

$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

文字列でkeyを指定することに加え、コールバックを渡すこともできます。コール―バックはグループとしてまとめるキーの値を返す必要があります。In addition to passing a string key, you may also pass a callback. The callback should return the value you wish to key the group by:

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['account_id'], -3);
});

$grouped->toArray();

/*
    [
        'x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

配列として、複数のグルーピング基準を指定できます。各配列要素は多次元配列の対応するレベルへ適用されます。Multiple grouping criteria may be passed as an array. Each array element will applied for the corresponding level within a multi-dimensional array:

$data = new Collection([
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
    40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);

$result = $data->groupBy([
    'skill',
    function ($item) {
        return $item['roles'];
    },
], $preserveKeys = true);

/*
[
    1 => [
        'Role_1' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_2' => [
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_3' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
        ],
    ],
    2 => [
        'Role_1' => [
            30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
        ],
        'Role_2' => [
            40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
        ],
    ],
];
*/

has() {#collection-method}has() {#collection-method}

hasメソッドは指定したキーがコレクションに存在しているかを調べます。The has method determines if a given key exists in the collection:

$collection = collect(['account_id' => 1, 'product' => 'Desk']);

$collection->has('product');

// true

implode() {#collection-method}implode() {#collection-method}

implodeメソッドはコレクションのアイテムを結合します。引数はコレクションのアイテムのタイプにより異なります。 コレクションに配列化オブジェクトが含まれている場合は、接続したい属性のキーと値の間にはさみたい「糊」の役割の文字列を指定します。The implode method joins the items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values:

$collection = collect([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);

$collection->implode('product', ', ');

// Desk, Chair

コレクションが文字列か数値を含んでいるだけなら、メソッドには「糊」の文字列を渡すだけで済みます。If the collection contains simple strings or numeric values, pass the "glue" as the only argument to the method:

collect([1, 2, 3, 4, 5])->implode('-');

// '1-2-3-4-5'

intersect() {#collection-method}intersect() {#collection-method}

intersectメソッドは、指定した「配列」かコレクションに存在していない値をオリジナルコレクションから取り除きます。結果のコレクションには、オリジナルコレクションのキーがリストされます。The intersect method removes any values from the original collection that are not present in the given array or collection. The resulting collection will preserve the original collection's keys:

$collection = collect(['Desk', 'Sofa', 'Chair']);

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']

intersectByKeys() {#collection-method}intersectByKeys() {#collection-method}

intersectByKeysメソッドは、指定した配列かコレクションに含まれないキーの要素をオリジナルコレクションから削除します。The intersectByKeys method removes any keys from the original collection that are not present in the given array or collection:

$collection = collect([
    'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);

$intersect = $collection->intersectByKeys([
    'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);

$intersect->all();

// ['type' => 'screen', 'year' => 2009]

isEmpty() {#collection-method}isEmpty() {#collection-method}

isEmptyメソッドはコレクションが空の場合にtrueを返します。そうでなければfalseを返します。The isEmpty method returns true if the collection is empty; otherwise, false is returned:

collect([])->isEmpty();

// true

isNotEmpty() {#collection-method}isNotEmpty() {#collection-method}

isNotEmptyメソッドは、コレクションが空でない場合にtrueを返します。空であればfalseを返します。The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:

collect([])->isNotEmpty();

// false

keyBy() {#collection-method}keyBy() {#collection-method}

keyByメソッドは指定したキーをコレクションのキーにします。複数のアイテムが同じキーを持っている場合、新しいコレクションには最後のアイテムが含まれます。The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$keyed = $collection->keyBy('product_id');

$keyed->all();

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

もしくは、コールバックをメソッドへ渡すこともできます。コールバックからコレクションのキーの値を返してください。You may also pass a callback to the method. The callback should return the value to key the collection by:

$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});

$keyed->all();

/*
    [
        'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

keys() {#collection-method}keys() {#collection-method}

keysメソッドはコレクションの全キーを返します。The keys method returns all of the collection's keys:

$collection = collect([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$keys = $collection->keys();

$keys->all();

// ['prod-100', 'prod-200']

last() {#collection-method}last() {#collection-method}

lastメソッドは指定したテストをパスしたコレクションの最後のアイテムを返します。The last method returns the last element in the collection that passes a given truth test:

collect([1, 2, 3, 4])->last(function ($value, $key) {
    return $value < 3;
});

// 2

またはlastメソッドを引数無しで呼び出し、コレクションの最後の要素を取得することもできます。コレクションが空の場合、nullが返ります。You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:

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

// 4

macro() {#collection-method}macro() {#collection-method}

staticのmacroメソッドで、実行時にCollectionクラスへメソッドを追加できます。詳細は、コレクションの拡張ドキュメントを参照してください。The static macro method allows you to add methods to the Collection class at run time. Refer to the documentation on extending collections[#extending-collections] for more information.

make() {#collection-method}make() {#collection-method}

staticのmakeメソッドは、新しいコレクションインスタンスを生成します。コレクションの生成セクションを参照してください。The static make method creates a new collection instance. See the Creating Collections[#creating-collections] section.

map() {#collection-method}map() {#collection-method}

mapメソッドコレクション全体を繰り返しで処理し、指定したコールバックから値を返します。コールバックで自由にアイテムを更新し値を返せます。更新したアイテムの新しいコレクションが作成されます。The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

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

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

Note: note 他のコレクションと同様にmapは新しいコレクションインスタンスを返します。呼び出し元のコレクションは変更しません。もしオリジナルコレクションを変更したい場合はtransformメソッドを使います。{note} Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the transform[#method-transform] method.

mapInto() {#collection-method}mapInto() {#collection-method}

mapInto()メソッドはコレクションを繰り返し処理します。指定したクラスの新しいインスタンスを生成し、コンストラクタへ値を渡します。The mapInto() method iterates over the collection, creating a new instance of the given class by passing the value into the constructor:

class Currency
{
    /**
     * Create a new currency instance.
     *
     * @param  string  $code
     * @return void
     */
    function __construct(string $code)
    {
        $this->code = $code;
    }
}

$collection = collect(['USD', 'EUR', 'GBP']);

$currencies = $collection->mapInto(Currency::class);

$currencies->all();

// [Currency('USD'), Currency('EUR'), Currency('GBP')]

mapSpread() {#collection-method}mapSpread() {#collection-method}

mapSpreadメソッドは指定したコールバックへ、コレクションのネストしたアイテム値をそれぞれ渡し、繰り返し処理します。値を変更した新しいコレクションを形成するために、コールバックで好きなようにアイテムを変更し、値を返してください。The mapSpread method iterates over the collection's items, passing each nested item value into the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunks = $collection->chunk(2);

$sequence = $chunks->mapSpread(function ($odd, $even) {
    return $odd   $even;
});

$sequence->all();

// [1, 5, 9, 13, 17]

mapToGroups() {#collection-method}mapToGroups() {#collection-method}

mapToGroupsメソッドは、指定したコールバックにより、コレクションアイテムを分類します。コールバックはキー/値ペアを一つ含む連想配列を返す必要があります。The mapToGroups method groups the collection's items by the given callback. The callback should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:

$collection = collect([
    [
        'name' => 'John Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Jane Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Johnny Doe',
        'department' => 'Marketing',
    ]
]);

$grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
});

$grouped->toArray();

/*
    [
        'Sales' => ['John Doe', 'Jane Doe'],
        'Marketing' => ['Johhny Doe'],
    ]
*/

$grouped->get('Sales')->all();

// ['John Doe', 'Jane Doe']

mapWithKeys() {#collection-method}mapWithKeys() {#collection-method}

mapWithKeysメソッドはコレクション全体を反復処理し、指定したコールバックへ各値を渡します。コールバックからキー/値ペアを一つ含む連想配列を返してください。The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com'
    ]
]);

$keyed = $collection->mapWithKeys(function ($item) {
    return [$item['email'] => $item['name']];
});

$keyed->all();

/*
    [
        'john@example.com' => 'John',
        'jane@example.com' => 'Jane',
    ]
*/

max() {#collection-method}max() {#collection-method}

maxメソッドは、指定したキーの最大値を返します。The max method returns the maximum value of a given key:

$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');

// 20

$max = collect([1, 2, 3, 4, 5])->max();

// 5

median() {#collection-method}median() {#collection-method}

medianメソッドは、指定したキーの中央値を返します。The median method returns the median value[https://en.wikipedia.org/wiki/Median] of a given key:

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

// 15

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

// 1.5

merge() {#collection-method}merge() {#collection-method}

mergeメソッドは、指定した配列かコレクションをオリジナルコレクションへマージします。指定した配列の文字列キーが、オリジナルコレクションの文字列キーと一致する場合、オリジナルコレクションの値は指定アイテムの値でオーバーライトされます。The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:

$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->merge(['price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => 1, price' => 200, 'discount' => false]

指定したアイテムのキーが数値の場合、コレクションの最後に追加されます。(訳注:数値でない場合の間違いか)If the given items's keys are numeric, the values will be appended to the end of the collection:

$collection = collect(['Desk', 'Chair']);

$merged = $collection->merge(['Bookcase', 'Door']);

$merged->all();

// ['Desk', 'Chair', 'Bookcase', 'Door']

min() {#collection-method}min() {#collection-method}

minメソッドは、指定したキーの最小値を返します。The min method returns the minimum value of a given key:

$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');

// 10

$min = collect([1, 2, 3, 4, 5])->min();

// 1

mode() {#collection-method}mode() {#collection-method}

modeメソッドは、指定したキーの最頻値を返します。The mode method returns the mode value[https://en.wikipedia.org/wiki/Mode_(statistics)] of a given key:

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

// [10]

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

// [1]

nth() {#collection-method}nth() {#collection-method}

nthメソッドは指定数値間隔で要素を含む、新しいコレクションを生成します。The nth method creates a new collection consisting of every n-th element:

$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

$collection->nth(4);

// ['a', 'e']

オプションとして第2引数にオフセットを渡せます。You may optionally pass an offset as the second argument:

$collection->nth(4, 1);

// ['b', 'f']

only() {#collection-method}only() {#collection-method}

onlyメソッドは、コレクション中の指定したアイテムのみを返します。The only method returns the items in the collection with the specified keys:

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

onlyの正反対の機能は、 exceptメソッドです。For the inverse of only, see the except[#method-except] method.

pad() {#collection-method}pad() {#collection-method}

padメソッドは、配列が指定したサイズに達するまで、指定値で配列を埋めます。このメソッドはarray_pad PHP関数のような動作をします。The pad method will fill the array with the given value until the array reaches the specified size. This method behaves like the array_pad[https://secure.php.net/manual/en/function.array-pad.php] PHP function.

先頭を埋めるためには、サイズに負数を指定します。配列サイズ以下のサイズ値を指定した場合は、埋め込みを行いません。To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array:

$collection = collect(['A', 'B', 'C']);

$filtered = $collection->pad(5, 0);

$filtered->all();

// ['A', 'B', 'C', 0, 0]

$filtered = $collection->pad(-5, 0);

$filtered->all();

// [0, 0, 'A', 'B', 'C']

partition() {#collection-method}partition() {#collection-method}

partitionメソッドは指定したテストの合否に要素を分け、結果をlist PHP関数で受け取ります。The partition method may be combined with the list PHP function to separate elements that pass a given truth test from those that do not:

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

list($underThree, $aboveThree) = $collection->partition(function ($i) {
    return $i < 3;
});

pipe() {#collection-method}pipe() {#collection-method}

pipeメソッドはコレクションを指定したコールバックに渡し、結果を返します。The pipe method passes the collection to the given callback and returns the result:

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

$piped = $collection->pipe(function ($collection) {
    return $collection->sum();
});

// 6

pluck() {#collection-method}pluck() {#collection-method}

pluckメソッドは指定したキーの全コレクション値を取得します。The pluck method retrieves all of the values for a given key:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

// ['Desk', 'Chair']

さらに、コレクションのキー項目も指定できます。You may also specify how you wish the resulting collection to be keyed:

$plucked = $collection->pluck('name', 'product_id');

$plucked->all();

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

pop() {#collection-method}pop() {#collection-method}

popメソッドはコレクションの最後のアイテムを削除し、返します。The pop method removes and returns the last item from the collection:

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

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

prepend() {#collection-method}prepend() {#collection-method}

prependメソッドはアイテムをコレクションの最初に追加します。The prepend method adds an item to the beginning of the collection:

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

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]

また、第2引数に追加するアイテムのキーを指定できます。You may also pass a second argument to set the key of the prepended item:

$collection = collect(['one' => 1, 'two' => 2]);

$collection->prepend(0, 'zero');

$collection->all();

// ['zero' => 0, 'one' => 1, 'two' => 2]

pull() {#collection-method}pull() {#collection-method}

pullメソッドはキーによりアイテムを削除し、そのアイテムを返します。The pull method removes and returns an item from the collection by its key:

$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);

$collection->pull('name');

// 'Desk'

$collection->all();

// ['product_id' => 'prod-100']

push() {#collection-method}push() {#collection-method}

pushメソッドはコレクションの最後にアイテムを追加します。The push method appends an item to the end of the collection:

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

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]

put() {#collection-method}put() {#collection-method}

putメソッドは指定したキーと値をコレクションにセットします。The put method sets the given key and value in the collection:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random() {#collection-method}random() {#collection-method}

randomメソッドはコレクションからランダムにアイテムを返します。The random method returns a random item from the collection:

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

$collection->random();

// 4 - (ランダムに取得)

オプションとして、randomにいくつのアイテムをランダムに取得するかを整数値で渡せます。受け取りたい数のアイテム数を明確に指定した場合、その数のコレクションのアイテムがいつも返されます。You may optionally pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:

$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (ランダムに取得)

コレクションが要求されたより少ないアイテムしか持っていない場合、このメソッドはInvalidArgumentExceptionを投げます。If the Collection has fewer items than requested, the method will throw an InvalidArgumentException.

reduce() {#collection-method}reduce() {#collection-method}

reduceメソッドは繰り返しの結果を次の繰り返しに渡しながら、コレクションを単一値へ減らします。The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

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

$total = $collection->reduce(function ($carry, $item) {
    return $carry   $item;
});

// 6

最初の繰り返しの$carryの値はnullです。しかし初期値を設定したい場合は、reduceの第2引数に渡してください。The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

$collection->reduce(function ($carry, $item) {
    return $carry   $item;
}, 4);

// 10

reject() {#collection-method}reject() {#collection-method}

rejectメソッドは指定したコールバックを使用し、コレクションをフィルタリングします。コールバックはコレクションの結果からアイテムを取り除く場合にtrueを返します。The reject method filters the collection using the given callback. The callback should return true if the item should be removed from the resulting collection:

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

$filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [1, 2]

rejectメソッドの逆の働きについては、filterメソッドを読んでください。For the inverse of the reject method, see the filter[#method-filter] method.

reverse() {#collection-method}reverse() {#collection-method}

reverseメソッドはオリジナルのキーを保ったまま、コレクションのアイテムの順番を逆にします。The reverse method reverses the order of the collection's items, preserving the original keys:

$collection = collect(['a', 'b', 'c', 'd', 'e']);

$reversed = $collection->reverse();

$reversed->all();

/*
    [
        4 => 'e',
        3 => 'd',
        2 => 'c',
        1 => 'b',
        0 => 'a',
    ]
*/

search() {#collection-method}search() {#collection-method}

searchメソッドは指定した値でコレクションをサーチし、見つけたキーを返します。アイテムが見つからない場合はfalseを返します。The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.

$collection = collect([2, 4, 6, 8]);

$collection->search(4);

// 1

検索は「緩い」比較で行われます。つまり、整数値を持つ文字列は、同じ値の整数と等しいと判断されます。「厳格」な比較を行いたい場合はtrueをメソッドの第2引数に渡します。The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use "strict" comparison, pass true as the second argument to the method:

$collection->search('4', true);

// false

別の方法としてサーチのコールバックを渡し、テストをパスした最初のアイテムを取得することもできます。Alternatively, you may pass in your own callback to search for the first item that passes your truth test:

$collection->search(function ($item, $key) {
    return $item > 5;
});

// 2

shift() {#collection-method}shift() {#collection-method}

shiftメソッドはコレクションから最初のアイテムを削除し、その値を返します。The shift method removes and returns the first item from the collection:

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

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

shuffle() {#collection-method}shuffle() {#collection-method}

shuffleメソッドはコレクションのアイテムをランダムにシャッフルします。The shuffle method randomly shuffles the items in the collection:

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

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (ランダムに生成される)

slice() {#collection-method}slice() {#collection-method}

sliceメソッドは指定したインデックスからコレクションを切り分けます。The slice method returns a slice of the collection starting at the given index:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$slice = $collection->slice(4);

$slice->all();

// [5, 6, 7, 8, 9, 10]

切り分ける数を制限したい場合は、メソッドの第2引数で指定してください。If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method:

$slice = $collection->slice(4, 2);

$slice->all();

// [5, 6]

sliceメソッドはデフォルトでキー値を保持したまま返します。オリジナルのキーを保持したくない場合は、valuesメソッドを使えば、インデックスし直されます。The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the values[#method-values] method to reindex them.

sort() {#collection-method}sort() {#collection-method}

sortメソッドはコレクションをソートします。ソート済みコレクションはオリジナル配列のキーを保持しますので、以下の例では、valuesメソッドにより、連続した数字のインデックスにするためリセットしています。The sort method sorts the collection. The sorted collection keeps the original array keys, so in this example we'll use the values[#method-values] method to reset the keys to consecutively numbered indexes:

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

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 2, 3, 4, 5]

より高度なソートを行いたい場合はsortにコールバックを渡し、自分のアルゴリズムを実行できます。コレクションのsortメソッドが裏で呼び出しているuasortのPHPドキュメントを参照してください。If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm. Refer to the PHP documentation on uasort[https://secure.php.net/manual/en/function.uasort.php#refsect1-function.uasort-parameters], which is what the collection's sort method calls under the hood.

lightbulb">Tip!! ネストした配列やオブジェクトのコレクションのソートは、sortBysortByDescメソッドを参照してください。{tip} If you need to sort a collection of nested arrays or objects, see the sortBy[#method-sortby] and sortByDesc[#method-sortbydesc] methods.

sortBy() {#collection-method}sortBy() {#collection-method}

sortByメソッドは指定したキーでコレクションをソートします。ソート済みコレクションはオリジナル配列のキーを保持しますので、以下の例では、valuesメソッドにより、連続した数字のインデックスにするためリセットしています。The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we'll use the values[#method-values] method to reset the keys to consecutively numbered indexes:

$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/

コレクション値をどのようにソートするかを決めるため、コールバックを渡すこともできます。You can also pass your own callback to determine how to sort the collection values:

$collection = collect([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/

sortByDesc() {#collection-method}sortByDesc() {#collection-method}

このメソッドの使い方はsortByと同じで、コレクションを逆順にソートします。This method has the same signature as the sortBy[#method-sortby] method, but will sort the collection in the opposite order.

splice() {#collection-method}splice() {#collection-method}

spliceメソッドは指定したインデックスからアイテムをスライスし、削除し、返します。The splice method removes and returns a slice of items starting at the specified index:

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

$chunk = $collection->splice(2);

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]

結果の塊の大きさを限定するために、第2引数を指定できます。You may pass a second argument to limit the size of the resulting chunk:

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

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]

さらに、コレクションから削除したアイテムに置き換える、新しいアイテムを第3引数に渡すこともできます。In addition, you can pass a third argument containing the new items to replace the items removed from the collection:

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

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 10, 11, 4, 5]

split() {#collection-method}split() {#collection-method}

splitメソッドは、コレクションを指定数のグループへ分割します。The split method breaks a collection into the given number of groups:

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

$groups = $collection->split(3);

$groups->toArray();

// [[1, 2], [3, 4], [5]]

sum() {#collection-method}sum() {#collection-method}

sumメソッドはコレクションの全アイテムの合計を返します。The sum method returns the sum of all items in the collection:

collect([1, 2, 3, 4, 5])->sum();

// 15

コレクションがネストした配列やオブジェクトを含んでいる場合、どの値を合計するのを決めるためにキーを指定してください。If the collection contains nested arrays or objects, you should pass a key to use for determining which values to sum:

$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);

$collection->sum('pages');

// 1272

さらに、コレクションのどの項目を合計するのかを決めるためにコールバックを渡すこともできます。In addition, you may pass your own callback to determine which values of the collection to sum:

$collection = collect([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$collection->sum(function ($product) {
    return count($product['colors']);
});

// 6

take() {#collection-method}take() {#collection-method}

takeメソッドは指定したアイテム数の新しいコレクションを返します。The take method returns a new collection with the specified number of items:

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

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

アイテム数に負の整数を指定した場合はコレクションの最後から取得します。You may also pass a negative integer to take the specified amount of items from the end of the collection:

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

$chunk = $collection->take(-2);

$chunk->all();

// [4, 5]

tap() {#collection-method}tap() {#collection-method}

tapメソッドは、指定されたコールバックへコレクションを渡します。コレクション自身に影響を与えることなく、その時点のコレクション内容を利用するために使用します。The tap method passes the collection to the given callback, allowing you to "tap" into the collection at a specific point and do something with the items while not affecting the collection itself:

collect([2, 4, 3, 1, 5])
    ->sort()
    ->tap(function ($collection) {
        Log::debug('Values after sorting', $collection->values()->toArray());
    })
    ->shift();

// 1

times() {#collection-method}times() {#collection-method}

静的timesメソッドは指定回数コールバックを呼び出すことで、新しいコレクションを生成します。The static times method creates a new collection by invoking the callback a given amount of times:

$collection = Collection::times(10, function ($number) {
    return $number * 9;
});

$collection->all();

// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

このメソッドはファクトリーと組み合わせ、Eloquentモデルを生成する場合に便利です。This method can be useful when combined with factories to create Eloquent[/docs/{{version}}/eloquent] models:

$categories = Collection::times(3, function ($number) {
    return factory(Category::class)->create(['name' => 'Category #'.$number]);
});

$categories->all();

/*
    [
        ['id' => 1, 'name' => 'Category #1'],
        ['id' => 2, 'name' => 'Category #2'],
        ['id' => 3, 'name' => 'Category #3'],
    ]
*/

toArray() {#collection-method}toArray() {#collection-method}

toArrayメソッドはコレクションをPHPの「配列」へ変換します。コレクションの値がEloquentモデルの場合は、そのモデルが配列に変換されます。The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent[/docs/{{version}}/eloquent] models, the models will also be converted to arrays:

$collection = collect(['name' => 'Desk', 'price' => 200]);

$collection->toArray();

/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/

Note: note toArrayはネストしたオブジェクトも全て配列へ変換します。裏の配列をそのまま取得したい場合は、代わりにallメソッドを使用してください。{note} toArray also converts all of the collection's nested objects to an array. If you want to get the raw underlying array, use the all[#method-all] method instead.

toJson() {#collection-method}toJson() {#collection-method}

toJsonメソッドはコレクションをシリアライズ済みのJSON文字へ変換します。The toJson method converts the collection into a JSON serialized string:

$collection = collect(['name' => 'Desk', 'price' => 200]);

$collection->toJson();

// '{"name":"Desk","price":200}'

transform() {#collection-method}transform() {#collection-method}

transformメソッドはコレクションを繰り返し処理し、コレクションの各アイテムに指定したコールバックを適用します。コレクション中のアイテムはコールバックから返される値に置き換わります。The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:

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

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]

Note: note 他のコレクションメソッドとは異なり、transformはコレクション自身を更新します。代わりに新しいコレクションを生成したい場合は、 mapメソッドを使用してください。{note} Unlike most other collection methods, transform modifies the collection itself. If you wish to create a new collection instead, use the map[#method-map] method.

union() {#collection-method}union() {#collection-method}

unionメソッドは指定した配列をコレクションへ追加します。既にコレクションにあるキーが、オリジナル配列に含まれている場合は、オリジナルコレクションの値が優先されます。The union method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection's values will be preferred:

$collection = collect([1 => ['a'], 2 => ['b']]);

$union = $collection->union([3 => ['c'], 1 => ['b']]);

$union->all();

// [1 => ['a'], 2 => ['b'], 3 => ['c']]

unique() {#collection-method}unique() {#collection-method}

uniqueメソッドはコレクションの重複を取り除いた全アイテムを返します。ソート済みのコレクションはオリジナルの配列キーを保っています。下の例ではvaluesメソッドで連続した数字のインデックスにするためリセットしています。The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in this example we'll use the values[#method-values] method to reset the keys to consecutively numbered indexes:

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

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]

ネストした配列やオブジェクトを取り扱いたい場合は、一意であることを決めるキーを指定する必要があります。When dealing with nested arrays or objects, you may specify the key used to determine uniqueness:

$collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);

$unique = $collection->unique('brand');

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/

アイテムが一意であるかを決めるコールバックを渡すこともできます。You may also pass your own callback to determine item uniqueness:

$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/

uniqueメソッドは、アイテムの判定に「緩い」比較を使用します。つまり、同じ値の文字列と整数値は等しいと判定します。「厳密」な比較でフィルタリングしたい場合は、uniqueStrictメソッドを使用してください。The unique method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the uniqueStrict[#method-uniquestrict] method to filter using "strict" comparisons.

uniqueStrict() {#collection-method}uniqueStrict() {#collection-method}

このメソッドは、uniqueと同じ使用方法です。しかし、全値は「厳密」に比較されます。This method has the same signature as the unique[#method-unique] method; however, all values are compared using "strict" comparisons.

unless() {#collection-method}unless() {#collection-method}

unlessメソッドは最初の引数がtrueと評価されなくなるまで、コールバックを実行します。The unless method will execute the given callback unless the first argument given to the method evaluates to true:

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

$collection->unless(true, function ($collection) {
    return $collection->push(4);
});

$collection->unless(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]

unlessの逆の動作は、whenメソッドです。For the inverse of unless, see the when[#method-when] method.

unwrap() {#collection-method}unwrap() {#collection-method}

staticのunwrapメソッドは適用可能な場合、指定値からコレクションの元になっているアイテムを返します。The static unwrap method returns the collection's underlying items from the given value when applicable:

Collection::unwrap(collect('John Doe'));

// ['John Doe']

Collection::unwrap(['John Doe']);

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'

values() {#collection-method}values() {#collection-method}

valuesメソッドはキーをリセット後、連続した整数にした新しいコレクションを返します。The values method returns a new collection with the keys reset to consecutive integers:

$collection = collect([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200]
]);

$values = $collection->values();

$values->all();

/*
    [
        0 => ['product' => 'Desk', 'price' => 200],
        1 => ['product' => 'Desk', 'price' => 200],
    ]
*/

when() {#collection-method}when() {#collection-method}

whenメソッドは、メソッドの第1引数がtrueに評価される場合、コールバックを実行します。The when method will execute the given callback when the first argument given to the method evaluates to true:

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

$collection->when(true, function ($collection) {
    return $collection->push(4);
});

$collection->when(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 4]

whenの逆の動作は、unlessメソッドです。For the inverse of when, see the unless[#method-unless] method.

where() {#collection-method}where() {#collection-method}

whereメソッドは指定したキー/値ペアでコレクションをフィルタリングします。The where method filters the collection by a given key / value pair:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereメソッドはアイテム値の確認を「緩く」比較します。つまり、同じ値の文字列と整数値は、同値と判断します。「厳格」な比較でフィルタリングしたい場合は、whereStrictメソッドを使ってください。The where method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereStrict[#method-wherestrict] method to filter using "strict" comparisons.

whereStrict() {#collection-method}whereStrict() {#collection-method}

このメソッドの使用法は、whereメソッドと同じです。しかし、値の比較はすべて「厳格」な比較で行われます。This method has the same signature as the where[#method-where] method; however, all values are compared using "strict" comparisons.

whereIn() {#collection-method}whereIn() {#collection-method}

whereInメソッドは指定された配列に含まれる値/キーにより、コレクションをフィルタリングします。The whereIn method filters the collection by a given key / value contained within the given array:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Desk', 'price' => 200],
    ]
*/

whereInメソッドはアイテム値のチェックを「緩く」比較します。つまり同じ値の文字列と整数値は同値と判定します。「厳密」な比較でフィルタリングしたい場合は、whereInStrictメソッドを使ってください。The whereIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereInStrict[#method-whereinstrict] method to filter using "strict" comparisons.

whereInStrict() {#collection-method}whereInStrict() {#collection-method}

このメソッドの使い方は、whereInメソッドと同じです。違いは全値を「厳密」に比較することです。This method has the same signature as the whereIn[#method-wherein] method; however, all values are compared using "strict" comparisons.

whereNotIn() {#collection-method}whereNotIn() {#collection-method}

whereNotInメソッドは、指定した配列中のキー/値を含まないコレクションをフィルタリングします。The whereNotIn method filters the collection by a given key / value not contained within the given array:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereNotInメソッドは、値を「緩く」比較します。つまり、同じ値の文字列と整数は、同値と判定されます。「厳密」にフィルタリングしたい場合は、whereNotInStrictメソッドを使用します。The whereNotIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereNotInStrict[#method-wherenotinstrict] method to filter using "strict" comparisons.

whereNotInStrict() {#collection-method}whereNotInStrict() {#collection-method}

このメソッドは、whereNotInと使い方は同じですが、全値の比較が「厳密」に行われる点が異なります。This method has the same signature as the whereNotIn[#method-wherenotin] method; however, all values are compared using "strict" comparisons.

wrap() {#collection-method}wrap() {#collection-method}

staticのwrapメソッドは適用可能であれば、指定値をコレクションでラップします。The static wrap method wraps the given value in a collection when applicable:

$collection = Collection::wrap('John Doe');

$collection->all();

// ['John Doe']

$collection = Collection::wrap(['John Doe']);

$collection->all();

// ['John Doe']

$collection = Collection::wrap(collect('John Doe'));

$collection->all();

// ['John Doe']

zip() {#collection-method}zip() {#collection-method}

zipメソッドは指定した配列の値と、対応するインデックスのオリジナルコレクションの値をマージします。The zip method merges together the values of the given array with the values of the original collection at the corresponding index:

$collection = collect(['Chair', 'Desk']);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [['Chair', 100], ['Desk', 200]]

Higher Order MessageHigher Order Messages

コレクションで繁用するアクションを手短に実行できるよう、"higher order messages"をサポートしました。averageavgcontainseacheveryfilterfirstflatMapmappartitionrejectsortBysortByDescsumuniqueコレクションメソッドでhigher order messageが使用できます。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, map, partition, reject, sortBy, sortByDesc, sum, and unique.

各higher order messageへは、コレクションインスタンスの動的プロパティとしてアクセスできます。例として、コレクション中の各オブジェクトメソッドを呼び出す、each higher order messageを使用してみましょう。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:

$users = User::where('votes', '>', 500)->get();

$users->each->markAsVip();

同様に、ユーザーのコレクションに対し、「投票(votes)」の合計数を求めるために、sum higher order messageを使用できます。Likewise, we can use the sum higher order message to gather the total number of "votes" for a collection of users:

$users = User::where('group', 'Development')->get();

return $users->sum->votes;

章選択

公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作