Laravel コレクションを単純に使用している場合は、map
次の手順を実行することでベース コレクションに簡単にアクセスできます。
$items = [ "dog", "cat", "unicorn" ];
collect($items)->map(function($item) use ($items) {
d($items); // Correctly outputs $items array
});
フィルター/拒否を伴う流暢なチェーンを使用している場合、 $items はもはやアイテムのセットを表していません:
$items = [ "dog", "cat", "unicorn" ];
collect($items)
->reject(function($item) {
// Reject cats, because they are most likely evil
return $item == 'cat';
})->map(function($item) use ($items) {
// Incorrectly (and obviously) outputs $items array (including "cat");
// Would like to see the $items (['dog', 'unicorn']) here
d($items);
// Will correctly dump 'dog' on iteration 0, and
// will correctly dump 'unicorn' on iteration 1
d($item);
});
質問
変更された項目配列にアクセスすることは可能ですか、それとも現在の状態でコレクションにアクセスすることはできますか?
lodash などの Javascript の同様のライブラリは、コレクションを 3 番目の引数として渡しますが、Laravel コレクションは渡しません。
更新/編集
明確にするために、次のようなことができます(ただし、チェーンを壊します)。次のことをしたいのですが、コレクションの中間ストレージはありません。
$items = [ "dog", "cat", "unicorn" ];
$items = collect($items)
->reject(function($item) {
// Reject cats, because they are most likely evil
return $item == 'cat';
});
$items->map(function($item) use ($items) {
// This will work (because I have reassigned
// the rejected sub collection to $items above)
d($items);
// Will correctly dump 'dog' on iteration 0, and
// will correctly dump 'unicorn' on iteration 1
d($item);
});