컬렉션
업데이트됨번역일: 2026년 9월 17일
이 페이지는 원문이 업데이트되어 번역이 갱신되었습니다.
- 원문 수정
- 2026년 9월 17일
- 번역 갱신
- 2026년 9월 17일
컬렉션
소개
Illuminate\Support\Collection 클래스는 배열을 다루는 작업을 더 편리하고 유연하게 만들어주는 래퍼(wrapper)입니다. 예를 들어 아래 코드를 살펴보겠습니다. collect 헬퍼를 사용해서 배열로부터 새로운 컬렉션 인스턴스를 생성하고, 각 요소에 strtoupper 함수를 적용한 다음, 비어 있는 요소를 모두 제거합니다.
$collection = collect(['taylor', 'abigail', null])->map(function (?string $name) {
return strtoupper($name);
})->reject(function (string $name) {
return empty($name);
});보시다시피 Collection 클래스는 메서드를 연달아 연결(체이닝)해서 내부 배열을 유연하게 매핑하고 축소(reduce)할 수 있게 해줍니다. 일반적으로 컬렉션은 불변(immutable)한 방식으로 동작합니다. 즉, 모든 Collection 메서드는 원본 컬렉션을 그대로 둔 채 완전히 새로운 Collection 인스턴스를 반환합니다.
NOTE
배열을 다루는 데 이렇게 강력한 도구가 필요한 경우가 흔치 않다고 생각할 수도 있습니다. 하지만 실제로 Laravel 컬렉션을 사용하다 보면, 순수 PHP 배열만으로는 처리하기 번거로웠던 작업들을 훨씬 간결하게 표현할 수 있다는 걸 금방 체감하게 됩니다. 특히 Eloquent 쿼리 결과가 대부분 Collection 인스턴스로 반환되기 때문에, 실전에서 컬렉션을 다룰 일이 매우 많습니다.
컬렉션 생성하기
앞서 언급했듯이, collect 헬퍼는 주어진 배열로부터 새로운 Illuminate\Support\Collection 인스턴스를 반환합니다. 즉, 컬렉션을 만드는 방법은 매우 간단합니다.
$collection = collect([1, 2, 3]);NOTE
Eloquent 쿼리 결과는 항상 Collection 인스턴스로 반환됩니다.
컬렉션 확장하기
컬렉션은 "매크로 사용 가능(macroable)"합니다. 즉, 런타임에 Collection 클래스에 추가 메서드를 등록할 수 있습니다. Illuminate\Support\Collection 클래스의 macro 메서드는 매크로가 호출될 때 실행할 클로저를 인자로 받습니다. 이 매크로 클로저는 해당 컬렉션 클래스의 다른 메서드에 접근하듯 $this를 통해 컬렉션의 실제 메서드에 접근할 수 있습니다. 예를 들어 아래 코드는 Collection 클래스에 toUpper 메서드를 추가합니다.
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Collection::macro('toUpper', function () {
return $this->map(function (string $value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']일반적으로 컬렉션 매크로는 하나의 서비스 프로바이더 내 boot 메서드에서 정의합니다.
매크로 인자
필요하다면 추가 인자를 받는 매크로를 정의할 수도 있습니다.
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
Collection::macro('toLocale', function (string $locale) {
return $this->map(function (string $value) use ($locale) {
return Lang::get($value, [], $locale);
});
});
$collection = collect(['first', 'second']);
$translated = $collection->toLocale('es');컬렉션
소개
Illuminate\Support\Collection 클래스는 배열 데이터를 다룰 때 유창하고(fluent) 편리하게 사용할 수 있는 래퍼(wrapper)를 제공합니다. 아래 예시 코드를 살펴보겠습니다. collect 헬퍼로 배열에서 새 컬렉션 인스턴스를 생성한 다음, 각 요소에 strtoupper 함수를 적용하고, 마지막으로 비어 있는 요소를 모두 제거합니다:
$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) {
return strtoupper($name);
})->reject(function (string $name) {
return empty($name);
});보시다시피 Collection 클래스는 메서드를 체이닝(chaining)해서 내부 배열에 대한 매핑과 축소(reduce) 작업을 유창하게 수행할 수 있게 해줍니다. 컬렉션은 기본적으로 불변(immutable)입니다. 즉, Collection의 모든 메서드는 원본을 수정하는 대신 완전히 새로운 Collection 인스턴스를 반환합니다.
NOTE
배열을 직접 조작하는 데 익숙하다면 다소 낯설게 느껴질 수 있습니다. 하지만 이런 불변성 덕분에 메서드 체이닝 중간에 원본 데이터가 예기치 않게 변경되는 실수를 방지할 수 있습니다.
컬렉션 생성하기
앞서 설명했듯, collect 헬퍼는 주어진 배열로부터 새로운 Illuminate\Support\Collection 인스턴스를 반환합니다. 컬렉션을 생성하는 방법은 다음과 같이 간단합니다:
$collection = collect([1, 2, 3]);이 외에도 make 메서드나 fromJson 메서드를 사용해 컬렉션을 생성할 수도 있습니다.
NOTE
Eloquent 쿼리의 조회 결과는 언제나 Collection 인스턴스로 반환됩니다.
컬렉션 확장하기
컬렉션은 "매크로화(macroable)"가 가능합니다. 즉, 런타임에 Collection 클래스에 새로운 메서드를 추가할 수 있습니다. Illuminate\Support\Collection 클래스의 macro 메서드는 매크로가 호출될 때 실행될 클로저를 인자로 받습니다. 이 클로저 안에서는 $this를 통해 컬렉션의 다른 메서드에 접근할 수 있는데, 마치 컬렉션 클래스에 실제로 정의된 메서드인 것처럼 동작합니다. 예를 들어, 다음 코드는 Collection 클래스에 toUpper 메서드를 추가합니다:
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Collection::macro('toUpper', function () {
return $this->map(function (string $value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']일반적으로 컬렉션 매크로는 서비스 프로바이더의 boot 메서드 안에 정의하는 것이 좋습니다.
매크로에 인자 전달하기
필요하다면 추가 인자를 받는 매크로를 정의할 수도 있습니다:
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
Collection::macro('toLocale', function (string $locale) {
return $this->map(function (string $value) use ($locale) {
return Lang::get($value, [], $locale);
});
});
$collection = collect(['first', 'second']);
$translated = $collection->toLocale('es');
// ['primero', 'segundo'];사용 가능한 메서드
지금부터 Collection 클래스에서 사용할 수 있는 각 메서드를 하나씩 살펴보겠습니다. 이 메서드들은 모두 체이닝(chaining)이 가능해서, 원본 배열을 자유롭게 가공할 수 있습니다. 또한 거의 모든 메서드가 새로운 Collection 인스턴스를 반환하기 때문에, 필요한 경우 원본 컬렉션을 그대로 보존할 수 있습니다.
NOTE
대부분의 메서드는 원본 컬렉션을 변경하지 않고 새 컬렉션을 반환합니다. 반면 transform, forget 등 일부 메서드는 컬렉션 자체를 직접 수정(mutate)하므로, 어떤 메서드가 "불변(immutable)"이고 어떤 메서드가 "가변(mutable)"인지 구분해 사용하는 것이 중요합니다.
after all average avg before chunk chunkBy chunkWhile collapse collapseWithKeys collect combine concat contains containsStrict count countBy crossJoin dd diff diffAssoc diffAssocUsing diffKeys doesntContain doesntContainStrict dot dump duplicates duplicatesStrict each eachSpread ensure every except filter first firstOrFail firstWhere flatMap flatten flip forget forPage fromJson get groupBy has hasAny hasMany hasSole implode intersect intersectUsing intersectAssoc intersectAssocUsing intersectByKeys isEmpty isNotEmpty join keyBy keys last lazy macro make map mapInto mapSpread mapToGroups mapWithKeys max median merge mergeRecursive min mode multiply nth only pad partition percentage pipe pipeInto pipeThrough pluck pop prepend pull push put random range reduce reduceInto reduceSpread reject replace replaceRecursive reverse search select shift shuffle skip skipUntil skipWhile slice sliding sole some sort sortBy sortByDesc sortDesc sortKeys sortKeysDesc sortKeysUsing splice split splitIn sum take takeUntil takeWhile tap times toArray toJson toPrettyJson transform undot union unique uniqueStrict unless unlessEmpty unlessNotEmpty unwrap value values when whenEmpty whenNotEmpty where whereStrict whereBetween whereIn whereInStrict whereInstanceOf whereNotBetween whereNotIn whereNotInStrict whereNotNull whereNull wrap zip
메서드 목록
`after()` {.collection-method .first-collection-method}
after 메서드는 주어진 항목 다음의 항목을 반환합니다. 주어진 항목을 찾을 수 없거나 마지막 항목인 경우 null이 반환됩니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->after(3);
// 4
$collection->after(5);
// null이 메서드는 "느슨한(loose)" 비교를 사용하여 주어진 항목을 검색합니다. 즉, 정수 값을 담고 있는 문자열은 같은 값을 가진 정수와 동일하다고 간주됩니다. "엄격한(strict)" 비교를 사용하려면 strict 인수를 메서드에 전달할 수 있습니다:
collect([2, 4, 6, 8])->after('4', strict: true);
// null또는, 주어진 진리 테스트를 통과하는 첫 번째 항목을 검색하기 위해 직접 클로저를 제공할 수도 있습니다:
collect([2, 4, 6, 8])->after(function (int $item, int $key) {
return $item > 5;
});
// 8`all()` {.collection-method}
all 메서드는 컬렉션이 나타내는 기본 배열을 반환합니다:
collect([1, 2, 3])->all();
// [1, 2, 3]`average()` {.collection-method}
avg 메서드의 별칭입니다.
`avg()` {.collection-method}
`avg` 메서드는 주어진 키의 [평균값](https://en.wikipedia.org/wiki/Average)을 반환합니다:$average = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->avg('foo');
// 20
$average = collect([1, 1, 2, 4])->avg();
// 2`before()` {.collection-method}
before 메서드는 after 메서드와 반대입니다. 주어진 항목 이전의 항목을 반환합니다. 주어진 항목을 찾을 수 없거나 첫 번째 항목인 경우 null이 반환됩니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->before(3);
// 2
$collection->before(1);
// null
collect([2, 4, 6, 8])->before('4', strict: true);
// null
collect([2, 4, 6, 8])->before(function (int $item, int $key) {
return $item > 5;
});
// 4`chunk()` {.collection-method}
chunk 메서드는 컬렉션을 주어진 크기의 여러 개의 더 작은 컬렉션으로 나눕니다:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->all();
// [[1, 2, 3, 4], [5, 6, 7]]이 메서드는 Bootstrap과 같은 그리드 시스템을 사용하는 뷰에서 작업할 때 특히 유용합니다. 예를 들어, 그리드에 표시하고 싶은 Eloquent 모델의 컬렉션이 있다고 가정해 봅시다:
@foreach ($products->chunk(3) as $chunk)
<div class="row">
```php
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach`chunkBy()` {.collection-method}
chunkBy 메서드는 주어진 키나 콜백에 대해 동일한 값을 가진 인접한 항목들을 그룹화하여 컬렉션을 여러 개의 더 작은 컬렉션으로 나눕니다. 예를 들어, 동일한 부모를 공유하는 인접한 상품들을 그룹화할 수 있습니다:
$chunks = $products->chunkBy('parent');groupBy 메서드와 달리, 동일한 값을 가지지만 인접하지 않은 항목들은 별도의 청크로 나뉩니다:
$collection = collect([1, 1, 2, 2, 1]);
$chunks = $collection->chunkBy(fn (int $value) => $value);
$chunks->all();
// [[1, 1], [2, 2], [1]]`chunkWhile()` {.collection-method}
chunkWhile 메서드는 주어진 콜백의 평가 결과에 따라 컬렉션을 여러 개의 더 작은 컬렉션으로 나눕니다. 클로저에 전달되는 $chunk 변수는 이전 요소를 확인하는 데 사용할 수 있습니다:
$collection = collect(str_split('AABBCCCD'));
$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {
return $value === $chunk->last();
});
$chunks->all();
// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]`collapse()` {.collection-method}
collapse 메서드는 배열이나 컬렉션들로 이루어진 컬렉션을 하나의 평평한(flat) 컬렉션으로 축소합니다:
$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]`collapseWithKeys()` {.collection-method}
collapseWithKeys 메서드는 배열이나 컬렉션의 컬렉션을 하나의 컬렉션으로 평탄화하면서, 원래의 키를 그대로 유지합니다. 컬렉션이 이미 평탄화되어 있다면 빈 컬렉션을 반환합니다:
$collection = collect([
['first' => collect([1, 2, 3])],
['second' => [4, 5, 6]],
['third' => collect([7, 8, 9])]
]);
$collapsed = $collection->collapseWithKeys();
$collapsed->all();
// [
// 'first' => [1, 2, 3],
// 'second' => [4, 5, 6],
// 'third' => [7, 8, 9],
// ]`collect()` {.collection-method}
collect 메서드는 현재 컬렉션에 있는 아이템으로 새로운 Collection 인스턴스를 반환합니다:
$collectionA = collect([1, 2, 3]);
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]collect 메서드는 지연 컬렉션을 표준 Collection 인스턴스로 변환할 때 특히 유용합니다:
$lazyCollection = LazyCollection::make(function () {
yield 1;
yield 2;
yield 3;
});
$collection = $lazyCollection->collect();
$collection::class;
// 'Illuminate\Support\Collection'
$collection->all();
// [1, 2, 3]NOTE
collect 메서드는 Enumerable의 인스턴스를 가지고 있고 지연(non-lazy) 컬렉션 인스턴스가 필요할 때 특히 유용합니다. collect()는 Enumerable 계약(contract)의 일부이므로, Collection 인스턴스를 얻는 데 안전하게 사용할 수 있습니다.
`combine()` {.collection-method}
combine 메서드는 컬렉션의 값들을 키로 사용하여 다른 배열이나 컬렉션의 값들과 결합합니다:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]`concat()` {.collection-method}
concat 메서드는 주어진 배열이나 컬렉션의 값들을 다른 컬렉션의 끝에 추가합니다:
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']concat 메서드는 원본 컬렉션에 연결된 항목들의 키를 숫자로 다시 인덱싱합니다. 연관 배열 컬렉션에서 키를 유지하려면 merge 메서드를 참고하세요.
`contains()` {.collection-method}
contains 메서드는 컬렉션이 주어진 항목을 포함하는지 여부를 판별합니다. 클로저를 contains 메서드에 전달하여 주어진 참/거짓 테스트와 일치하는 요소가 컬렉션에 존재하는지 판별할 수도 있습니다:
$collection = collect([1, 2, 3, 4, 5]);
```php
$collection->contains(function (int $value, int $key) {
return $value > 5;
});
// false또는 contains 메서드에 문자열을 전달하여 컬렉션이 주어진 항목 값을 포함하는지 확인할 수도 있습니다:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// falsecontains 메서드에 키 / 값 쌍을 전달하여 주어진 쌍이 컬렉션에 존재하는지 확인할 수도 있습니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// falsecontains 메서드는 항목 값을 확인할 때 "느슨한(loose)" 비교를 사용합니다. 즉, 정수값을 가진 문자열은 동일한 값을 가진 정수와 같은 것으로 간주됩니다. "엄격한(strict)" 비교를 사용하여 필터링하려면 containsStrict 메서드를 사용하세요.
contains의 반대 동작을 원한다면 doesntContain 메서드를 참고하세요.
`containsStrict()` {.collection-method}
이 메서드는 contains 메서드와 시그니처가 동일하지만, 모든 값이 "엄격한(strict)" 비교를 사용하여 비교됩니다.
NOTE
이 메서드의 동작은 Eloquent 컬렉션을 사용할 때 변경됩니다.
`count()` {.collection-method}
```php $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'], ] */
<h4 id="method-diffassocusing">`dd()` {.collection-method}</h4>
The `dd` method dumps the collection's items and ends execution of the script:
```php
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/If you do not want to stop executing the script, use the dump method instead.
`diff()` {.collection-method}
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]NOTE
`diffAssoc()` {.collection-method}
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,
]);
$diff->all();
// ['color' => 'orange', 'remain' => 6]`diffAssocUsing()` {.collection-method}
Unlike diffAssoc, diffAssocUsing accepts a user supplied callback function for the key comparison:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$diff = $collection->diffAssocUsing([
'Color' => 'yellow',
'Type' => 'fruit',
'Remain' => 3,
], 'strcasecmp');
$diff->all();
// ['color' => 'orange', 'remain' => 6]The callback should be a comparison function that returns an integer less than, equal to, or greater than zero. For more info, refer to the PHP documentation on array_diff_uassoc, which is the PHP function that diffAssocUsing method utilizes internally.
`diffKeys()` {.collection-method}
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]`doesntContain()` {.collection-method}
The doesntContain method determines whether the collection does not contain a given item. You may pass a closure to the doesntContain method to determine if an element does not exist in the collection matching a given truth test:
$collection = collect([1, 2, 3, 4, 5]);
$collection->doesntContain(function (int $value, int $key) {
return $value < 5;
});
// falseAlternatively, you may pass a string to the doesntContain method to determine whether the collection does not contain a given item value:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->doesntContain('Table');
// true
$collection->doesntContain('Desk');
// falseYou may also pass a key / value pair to the doesntContain method, which will determine if the given pair does not exist in the collection:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->doesntContain('product', 'Bookcase');
// trueThe doesntContain 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 doesntContainStrict method to filter using "strict" comparisons.
`doesntContainStrict()` {.collection-method}
This method has the same signature as the doesntContain method; however, all values are compared using "strict" comparisons.
NOTE
This method's behavior is modified when using Eloquent Collections.
`dump()` {.collection-method}
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"
]
}
*/If you want to stop executing the script after dumping the collection, use the dd method instead.
`duplicates()` {.collection-method}
The duplicates method retrieves and returns duplicate values from the collection:
$collection = collect(['a', 'b', 'a', 'c', 'b']);
$collection->duplicates();
// [2 => 'a', 4 => 'b']If the collection contains arrays or objects, you can pass the key of the attributes that you wish to check for duplicate values:
$employees = collect([
['email' => 'abigail@example.com', 'position' => 'Developer'],
['email' => 'james@example.com', 'position' => 'Designer'],
['email' => 'victoria@example.com', 'position' => 'Developer'],
]);
$employees->duplicates('position');
// [2 => 'Developer']`duplicatesStrict()` {.collection-method}
This method has the same signature as the duplicates method; however, all values are compared using "strict" comparisons.
`each()` {.collection-method}
The each method iterates over the items in the collection and passes each item to a closure:
$collection = collect([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
// ...
});If you would like to stop iterating through the items, you may return false from your closure:
$collection->each(function (int $item, int $key) {
if (/* condition */) {
return false;
}
});`eachSpread()` {.collection-method}
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 (string $name, int $age) {
// ...
});You may stop iterating through the items by returning false from the callback:
$collection->eachSpread(function (string $name, int $age) {
return false;
});`ensure()` {.collection-method}
The ensure method may be used to verify that all elements of a collection are of a given type or list of types. Otherwise, an UnexpectedValueException will be thrown:
return $collection->ensure(User::class);
return $collection->ensure([User::class, Customer::class]);Primitive types such as string, int, float, bool, and array may also be specified:
return $collection->ensure('int');WARNING
The ensure method does not guarantee that elements of different types will not be added to the collection at a later time.
`every()` {.collection-method}
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 (int $value, int $key) {
return $value > 2;
});
// falseIf the collection is empty, the every method will return true:
$collection = collect([]);
$collection->every(function (int $value, int $key) {
return $value > 2;
});
// true [1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/`dd()` {.collection-method}
dd 메서드는 컬렉션의 아이템들을 덤프하고 스크립트 실행을 종료합니다:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
*/스크립트 실행을 멈추고 싶지 않다면 대신 dump 메서드를 사용하세요.
`diff()` {.collection-method}
diff 메서드는 컬렉션을 다른 컬렉션이나 일반 PHP array와 값을 기준으로 비교합니다. 이 메서드는 주어진 컬렉션에 존재하지 않는 원본 컬렉션의 값들을 반환합니다:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]NOTE
이 메서드의 동작은 Eloquent 컬렉션을 사용할 때 변경됩니다.
`diffAssoc()` {.collection-method}
diffAssoc 메서드는 컬렉션을 다른 컬렉션이나 일반 PHP array와 키 및 값을 기준으로 비교합니다. 이 메서드는 주어진 컬렉션에 존재하지 않는 원본 컬렉션의 키 / 값 쌍을 반환합니다:
$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]`diffAssocUsing()` {.collection-method}
diffAssoc와 달리, diffAssocUsing은 인덱스 비교를 위해 사용자가 제공한 콜백 함수를 받습니다:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$diff = $collection->diffAssocUsing([
'Color' => 'yellow',
'Type' => 'fruit',
'Remain' => 3,
], 'strnatcasecmp');
$diff->all();
// ['color' => 'orange', 'remain' => 6]콜백은 0보다 작거나, 같거나, 큰 정수를 반환하는 비교 함수여야 합니다. 자세한 내용은 diffAssocUsing 메서드가 내부적으로 사용하는 PHP 함수인 array_diff_uassoc에 대한 PHP 문서를 참고하십시오.
`diffKeys()` {.collection-method}
diffKeys 메서드는 컬렉션을 키를 기준으로 다른 컬렉션이나 일반 PHP array와 비교합니다. 이 메서드는 원본 컬렉션에 있지만 주어진 컬렉션에는 없는 키 / 값 쌍을 반환합니다:
$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]
<h4 id="method-flip">`doesntContain()` {.collection-method}</h4>
`doesntContain` 메서드는 컬렉션이 주어진 항목을 포함하지 않는지 여부를 판단합니다. 클로저를 `doesntContain` 메서드에 전달하여 주어진 진위 테스트와 일치하는 요소가 컬렉션에 존재하지 않는지 판단할 수 있습니다:
```php
$collection = collect([1, 2, 3, 4, 5]);
$collection->doesntContain(function (int $value, int $key) {
return $value < 5;
});
// false또는, 문자열을 doesntContain 메서드에 전달하여 컬렉션이 주어진 항목 값을 포함하지 않는지 판단할 수 있습니다:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->doesntContain('Table');
// true
$collection->doesntContain('Desk');
// false키 / 값 쌍을 doesntContain 메서드에 전달할 수도 있으며, 이 경우 주어진 쌍이 컬렉션에 존재하지 않는지 판단합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->doesntContain('product', 'Bookcase');
// truedoesntContain 메서드는 항목 값을 확인할 때 "느슨한" 비교를 사용합니다. 즉, 정수 값을 가진 문자열은 동일한 값을 가진 정수와 동일한 것으로 간주됩니다.
['email' => 'james@example.com', 'position' => 'Designer'],
['email' => 'victoria@example.com', 'position' => 'Developer'],
]);
$employees->duplicates('position');
// [2 => 'Developer']`duplicatesStrict()` {.collection-method}
This method has the same signature as the duplicates method; however, all values are compared using "strict" comparisons.
`each()` {.collection-method}
The each method iterates over the items in the collection and passes each item to a closure:
$collection = collect([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
// ...
});If you would like to stop iterating through the items, you may return false from your closure:
$collection->each(function (int $item, int $key) {
if (/* condition */) {
return false;
}
});`eachSpread()` {.collection-method}
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 (string $name, int $age) {
// ...
});You may stop iterating through the items by returning false from the callback:
$collection->eachSpread(function (string $name, int $age) {
return false;
});`ensure()` {.collection-method}
The ensure method may be used to verify that all elements of a collection are of a given type or list of types. Otherwise, an UnexpectedValueException will be thrown:
return $collection->ensure(User::class);
return $collection->ensure([User::class, Customer::class]);Primitive types such as string, int, float, bool, and array may also be specified:
return $collection->ensure('int');WARNING
The ensure method does not guarantee that elements of different types will not be added to the collection at a later time.
`every()` {.collection-method}
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 (int $value, int $key) {
return $value > 2;
});
// falseIf the collection is empty, the every method will return true:
$collection = collect([]);
$collection->every(function (int $value, int $key) {
return $value > 2;
});
// true`except()` {.collection-method}
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]For the inverse of except, see the only method.
NOTE
This method's behavior is modified when using Eloquent Collections.
`filter()` {.collection-method}
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 (int $value, int $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]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]For the inverse of filter, see the reject method.
`first()` {.collection-method}
The first method returns the first element in the collection that passes a given truth test:
collect([1, 2, 3, 4])->first(function (int $value, int $key) {
return $value > 2;
});
// 3You 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`firstOrFail()` {.collection-method}
The firstOrFail method is identical to the first method; however, if no result is found, an \Illuminate\Support\ItemNotFoundException exception will be thrown:
collect([1, 2, 3, 4])->firstOrFail(function (int $value, int $key) {
return $value > 5;
});
// Throws ItemNotFoundException...You may also call the firstOrFail method with no arguments to get the first element in the collection. If the collection is empty, an \Illuminate\Support\ItemNotFoundException exception will be thrown:
collect([])->firstOrFail();
// Throws ItemNotFoundException...`firstWhere()` {.collection-method}
The firstWhere method returns the first element in the collection with the given key / value pair:
$collection = collect([
['name' => 'Regena', 'age' => null],
['name' => 'Linda', 'age' => 14],
['name' => 'Diego', 'age' => 23],
['name' => 'Linda', 'age' => 84],
]);
$collection->firstWhere('name', 'Linda');
// ['name' => 'Linda', 'age' => 14]You may also call the firstWhere method with a comparison operator:
$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]Like the where method, you may pass one argument to the firstWhere method. In this scenario, the firstWhere method will return the first item where the given item key's value is "truthy":
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]`flatMap()` {.collection-method}
The flatMap method iterates through the collection and passes each nested item value to a given closure. The closure 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 (array $values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];`flatten()` {.collection-method}
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'];If necessary, you may pass the flatten method 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'],
]
*/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 specify the number of levels nested arrays will be flattened.
`flip()` {.collection-method}
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}
The forget method removes an item from the collection by its key:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
// Forget a single key...
$collection->forget('name');
// ['framework' => 'laravel']
// Forget multiple keys...
$collection->forget(['name', 'framework']);
// []WARNING
Unlike most other collection methods, forget does not return a new modified collection; it modifies the collection it is called on.
`forPage()` {.collection-method}
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}
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');
// taylorYou may pass a default value as the second argument:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('age', 34);
// 34You may even pass a callback as the method's default value. The result of the callback will be returned if the specified key does not exist:
$collection->get('email', function () {
return 'taylor@example.com';
});
// taylor@example.com`groupBy()` {.collection-method}
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->all();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/Instead of passing a string key, you may pass a callback. The callback should return the value you wish to key the group by:
$grouped = $collection->groupBy(function (array $item, int $key) {
return substr($item['account_id'], -3);
});
$grouped->all();
/*
[
'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 be applied to 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 (array $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}
The has method determines if a given key exists in the collection:
$collection = collect(['account_id' => 1, 'product' => 'Desk']);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// false`hasAny()` {.collection-method}
The hasAny method determines if any of the given keys exist in the collection:
$collection = collect(['account_id' => 1, 'product' => 'Desk']);
$collection->hasAny(['product', 'amount']);
// true
$collection->hasAny(['name', 'amount']);
// false`implode()` {.collection-method}
The implode method joins 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, ChairIf the collection contains simple strings or numeric values, you should pass the "glue" as the only argument to the method:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'You may pass a closure to the implode method if you would like to format the values being imploded:
$collection->implode(function (array $item, int $key) {
return strtoupper($item['product']);
}, ', ');
// DESK, CHAIR['email' => 'james@example.com', 'position' => 'Designer'], ['email' => 'victoria@example.com', 'position' => 'Developer'], ]);
$employees->duplicates('position');
// [2 => 'Developer']
<h4 id="method-last">`duplicatesStrict()` {.collection-method}</h4>
이 메서드는 [duplicates](#method-doesntcontain) 메서드와 시그니처가 동일하지만, 모든 값을 "엄격한(strict)" 비교로 비교합니다.
<h4 id="method-lazy">`each()` {.collection-method}</h4>
`each` 메서드는 컬렉션의 아이템을 순회하며 각 아이템을 클로저에 전달합니다:
```php
$collection = collect([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
// ...
});아이템 순회를 중단하고 싶다면, 클로저에서 false를 반환하면 됩니다:
$collection->each(function (int $item, int $key) {
if (/* 조건 */) {
return false;
}
});`eachSpread()` {.collection-method}
eachSpread 메서드는 컬렉션의 아이템을 순회하며, 중첩된 각 아이템 값을 지정한 콜백에 전달합니다:
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function (string $name, int $age) {
// ...
});콜백에서 false를 반환하여 아이템 순회를 중단할 수 있습니다:
$collection->eachSpread(function (string $name, int $age) {
return false;
});`ensure()` {.collection-method}
ensure 메서드는 컬렉션의 모든 요소가 지정된 타입 또는 타입 목록에 해당하는지 확인하는 데 사용할 수 있습니다. 그렇지 않으면 UnexpectedValueException이 발생합니다:
return $collection->ensure(User::class);
return $collection->ensure([User::class, Customer::class]);string, int, float, bool, array와 같은 기본 타입도 지정할 수 있습니다:
return $collection->ensure('int');WARNING
ensure 메서드는 이후에 다른 타입의 요소가 컬렉션에 추가되지 않는다는 것을 보장하지는 않습니다.
`every()` {.collection-method}
every 메서드는 컬렉션의 모든 요소가 주어진 진리 테스트를 통과하는지 확인하는 데 사용할 수 있습니다:
collect([1, 2, 3, 4])->every(function (int $value, int $key) {
return $value > 2;
});
// false컬렉션이 비어 있으면 every 메서드는 true를 반환합니다:
$collection = collect([]);
$collection->every(function (int $value, int $key) {
return $value > 2;
});
// true`except()` {.collection-method}
except 메서드는 지정된 키를 가진 항목을 제외한 컬렉션의 모든 항목을 반환합니다:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]except의 반대 동작은 only 메서드를 참고하세요.
NOTE
이 메서드는 Eloquent 컬렉션을 사용할 때 동작 방식이 달라집니다.
`filter()` {.collection-method}
filter 메서드는 주어진 콜백을 사용하여 컬렉션을 필터링하며, 주어진 진리 테스트를 통과하는 항목만 남깁니다:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function (int $value, int $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]콜백이 제공되지 않으면, 컬렉션의 false와 동등한 모든 항목이 제거됩니다:
$collection = collect([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// [1, 2, 3]filter의 반대 동작은 reject 메서드를 참고하세요.
`first()` {.collection-method}
first 메서드는 주어진 진리 테스트를 통과하는 컬렉션의 첫 번째 요소를 반환합니다:
collect([1, 2, 3, 4])->first(function (int $value, int $key) {
return $value > 2;
});
// 3인수 없이 first 메서드를 호출하여 컬렉션의 첫 번째 요소를 가져올 수도 있습니다. 컬렉션이 비어 있으면 null이 반환됩니다:
collect([1, 2, 3, 4])->first();
// 1`firstOrFail()` {.collection-method}
`firstOrFail` 메서드는 `first` 메서드와 동일하지만, 결과를 찾을 수 없는 경우 `Illuminate\Support\ItemNotFoundException` 예외가 발생합니다:collect([1, 2, 3, 4])->firstOrFail(function (int $value, int $key) {
return $value > 5;
});
// Throws ItemNotFoundException...인수 없이 firstOrFail 메서드를 호출하여 컬렉션의 첫 번째 요소를 가져올 수도 있습니다. 컬렉션이 비어 있는 경우 Illuminate\Support\ItemNotFoundException 예외가 발생합니다:
collect([])->firstOrFail();
// Throws ItemNotFoundException...`firstWhere()` {.collection-method}
firstWhere 메서드는 주어진 키 / 값 쌍을 가진 컬렉션의 첫 번째 요소를 반환합니다:
$collection = collect([
['name' => 'Regena', 'age' => null],
['name' => 'Linda', 'age' => 14],
['name' => 'Diego', 'age' => 23],
['name' => 'Linda', 'age' => 84],
]);
$collection->firstWhere('name', 'Linda');
// ['name' => 'Linda', 'age' => 14]firstWhere 메서드를 비교 연산자와 함께 호출할 수도 있습니다:
$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]where 메서드와 마찬가지로, firstWhere 메서드에 하나의 인수를 전달할 수 있습니다. 이 경우 firstWhere 메서드는 주어진 항목 키의 값이 "참"(truthy)인 첫 번째 항목을 반환합니다:
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]`flatMap()` {.collection-method}
flatMap 메서드는 컬렉션을 순회하면서 각 값을 주어진 클로저에 전달합니다. 클로저는 아이템을 자유롭게 수정하고 반환할 수 있으며, 이렇게 수정된 아이템들로 새로운 컬렉션이 만들어집니다. 그런 다음 배열은 한 단계만큼 평탄화됩니다:
$collection = collect([
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
]);
$flattened = $collection->flatMap(function (array $values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];`flatten()` {.collection-method}
flatten 메서드는 다차원 컬렉션을 단일 차원으로 평탄화합니다:
$collection = collect([
'name' => 'Taylor',
'languages' => [
'PHP', 'JavaScript'
]
]);
$flattened = $collection->flatten();
$flattened->all();
// ['Taylor', 'PHP', 'JavaScript'];필요한 경우, flatten 메서드에 "깊이(depth)" 인자를 전달할 수 있습니다:
$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'],
```php
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/이 예시에서 깊이를 지정하지 않고 flatten을 호출했다면 중첩된 배열도 평탄화되어 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']이 되었을 것입니다. 깊이를 지정하면 중첩된 배열이 몇 단계까지 평탄화될지 지정할 수 있습니다.
`flip()` {.collection-method}
flip 메서드는 컬렉션의 키와 그에 대응하는 값을 서로 바꿉니다:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['Taylor' => 'name', 'Laravel' => 'framework']`forget()` {.collection-method}
forget 메서드는 키를 기준으로 컬렉션에서 항목을 제거합니다:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
// 단일 키를 제거...
$collection->forget('name');
// ['framework' => 'Laravel']
// 여러 개의 키를 제거...
$collection->forget(['name', 'framework']);
// []WARNING
대부분의 다른 컬렉션 메서드와 달리, forget은 수정된 새로운 컬렉션을 반환하지 않습니다. 대신 호출된 컬렉션 자체를 수정하고 반환합니다.
`forPage()` {.collection-method}
``` // email@example.com ````groupBy()` {.collection-method}
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->all();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/Instead of passing a string key, you may 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->all();
/*
[
'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 be applied to 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}
The has method determines if a given key exists in the collection:
$collection = collect(['account_id' => 1, 'product' => 'Desk']);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// false`hasAny()` {.collection-method}
The hasAny method determines if any of the given keys exist in the collection:
$collection = collect(['account_id' => 1, 'product' => 'Desk']);
$collection->hasAny(['product', 'amount']);
// true
$collection->hasAny(['name', 'amount']);
// false`implode()` {.collection-method}
The implode method joins 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, ChairIf the collection contains simple strings or numeric values, you should pass the "glue" as the only argument to the method:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'You may pass a closure to the implode method if you would like to format the values being imploded:
$collection->implode(function ($item, $key) {
return strtoupper($item['product']);
}, ', ');
// DESK, CHAIR`intersect()` {.collection-method}
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']NOTE
When working with Eloquent collections, the intersect method's behavior changes.
`intersectAssoc()` {.collection-method}
The intersectAssoc method compares the original collection against another collection or PHP array, returning the key / value pairs that are present in all of the given collections:
$collection = collect([
'color' => 'red',
'size' => 'M',
'material' => 'cotton'
]);
$intersect = $collection->intersectAssoc([
'color' => 'blue',
'size' => 'M',
'material' => 'polyester'
]);
$intersect->all();
// ['size' => 'M']`intersectByKeys()` {.collection-method}
The intersectByKeys method removes any keys and their corresponding values 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}
The isEmpty method returns true if the collection is empty; otherwise, false is returned:
collect([])->isEmpty();
// true`isNotEmpty()` {.collection-method}
The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:
collect([])->isNotEmpty();
// false`join()` {.collection-method}
The join method joins the collection's values with a string. Using this method's second argument, you may also specify how the final element should be appended to the string:
collect(['a', 'b', 'c'])->join(', ');
// 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and ');
// 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and ');
// 'a and b'
collect(['a'])->join(', ', ' and ');
// 'a'
collect([])->join(', ', ' and ');
// ''`keyBy()` {.collection-method}
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 your own 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}
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}
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;
});
// 2You 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`lazy()` {.collection-method}
The lazy method returns a new LazyCollection instance from the underlying array of items:
$lazyCollection = collect([1, 2, 3, 4])->lazy();
$lazyCollection::class;
// Illuminate\Support\LazyCollection
$lazyCollection->all();
// [1, 2, 3, 4]This is especially useful when you need to perform transformations on a huge Collection that contains many items:
$count = $hugeCollection
->lazy()
->where('country', 'FR')
->where('balance', '>', '100')
->count();By converting the collection to a LazyCollection, we avoid having to allocate a ton of additional memory. Though the original collection still keeps its values in memory, the subsequent filters do not. Therefore, virtually no additional memory will be allocated when Laravel filters the collection's results.
`macro()` {.collection-method}
The static macro method allows you to add methods to the Collection class at run time. Refer to the documentation on extending collections for more information.
`make()` {.collection-method}
The static make method creates a new collection instance. See the Creating Collections section.
`map()` {.collection-method}
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]WARNING
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.
`mapInto()` {.collection-method}
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.
*/
function __construct(
public string $code,
) {}
}$collection = collect(['USD', 'EUR', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('USD'), Currency('EUR'), Currency('GBP')]`mapSpread()` {.collection-method}
The mapSpread method iterates over the collection's items, passing each nested item value into the given closure. The closure 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 ($even, $odd) {
return $even + $odd;
});
$sequence->all();
// [1, 5, 9, 13, 17]`mapToGroups()` {.collection-method}
The mapToGroups method groups the collection's items by the given closure. The closure 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->all();
/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']`mapWithKeys()` {.collection-method}
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, $key) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/`max()` {.collection-method}
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}
The median method returns the median value 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}
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']`mergeRecursive()` {.collection-method}
The mergeRecursive method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->mergeRecursive([
'product_id' => 2,
'price' => 200,
'discount' => false
]);
$merged->all();
// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]`min()` {.collection-method}
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}
The mode method returns the mode value 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}
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']You may optionally pass a starting offset as the second argument:
$collection->nth(4, 1);
// ['b', 'f']`only()` {.collection-method}
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']For the inverse of only, see the except method.
NOTE
When working with Eloquent collections, the only method's behavior changes.
`pad()` {.collection-method}
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 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']컬렉션
// taylor@example.com`groupBy()` {.collection-method}
groupBy 메서드는 주어진 키로 컬렉션의 항목을 그룹화합니다:
$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->all();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/문자열 key를 전달하는 대신, 콜백을 전달할 수도 있습니다. 콜백은 그룹화하고자 하는 키의 값을 반환해야 합니다:
$grouped = $collection->groupBy(function (array $item, int $key) {
return substr($item['account_id'], -3);
});
$grouped->all();
/*
[
'x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/여러 그룹화 기준을 배열로 전달할 수도 있습니다. 각 배열 요소는 다차원 배열 내 해당하는 레벨에 적용됩니다:
$data = new Collection([
<h4 id="method-sliding">`has()` {.collection-method}</h4>
`has` 메서드는 컬렉션에 주어진 키가 존재하는지 확인합니다:
```php
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// true
$collection->has(['amount', 'price']);
// false`hasAny()` {.collection-method}
`hasAny` 메서드는 주어진 키들 중 하나라도 컬렉션에 존재하는지 확인합니다:$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->hasAny(['product', 'price']);
// true
$collection->hasAny(['name', 'price']);
// false`hasMany()` {.collection-method}
hasMany 메서드는 컬렉션이 여러 개의 항목을 포함하고 있는지 확인합니다:
collect([])->hasMany();
// false
collect(['1'])->hasMany();
// false
collect([1, 2, 3])->hasMany();
// true
collect([
['age' => 2],
['age' => 3],
])->hasMany(fn ($item) => $item['age'] === 2);
// false`hasSole()` {.collection-method}
hasSole 메서드는 컬렉션이 (선택적으로 주어진 조건과 일치하는) 단일 항목을 포함하고 있는지 확인합니다:
collect([])->hasSole();
// false
collect(['1'])->hasSole();
// true
collect([1, 2, 3])->hasSole(fn (int $item) => $item === 2);
// true`implode()` {.collection-method}
implode 메서드는 컬렉션의 항목들을 하나로 결합합니다. 인수는 컬렉션에 포함된 항목의 유형에 따라 달라집니다. 컬렉션이 배열이나 객체를 포함하는 경우, 결합하고자 하는 속성의 키와 값들 사이에 위치시킬 "접착제(glue)" 문자열을 전달해야 합니다:
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
```php
$collection->implode('product', ', ');
// 'Desk, Chair'컬렉션에 단순 문자열이나 숫자 값이 들어있다면, "glue"를 유일한 인자로 메서드에 전달하면 됩니다:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'implode로 합쳐질 값을 포맷하고 싶다면 implode 메서드에 클로저를 전달할 수 있습니다:
$collection->implode(function (array $item, int $key) {
return strtoupper($item['product']);
}, ', ');
// 'DESK, CHAIR'`intersect()` {.collection-method}
intersect 메서드는 원본 컬렉션에서 주어진 배열이나 컬렉션에 존재하지 않는 값들을 제거합니다. 결과로 반환되는 컬렉션은 원본 컬렉션의 키를 그대로 유지합니다:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']NOTE
이 메서드는 Eloquent 컬렉션을 사용할 때 동작이 변경됩니다.
`intersectUsing()` {.collection-method}
intersectUsing 메서드는 원본 컬렉션에서 주어진 배열이나 컬렉션에 존재하지 않는 값들을, 값을 비교하는 커스텀 콜백을 사용하여 제거합니다. 결과로 반환되는 컬렉션은 원본 컬렉션의 키를 그대로 유지합니다:
$collection = collect(['Desk', 'Sofa', 'Chair']);
```php
$intersect = $collection->intersectUsing(['desk', 'chair', 'bookcase'], function (string $a, string $b) {
return strcasecmp($a, $b);
});
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']`intersectAssoc()` {.collection-method}
intersectAssoc 메서드는 원본 컬렉션을 다른 컬렉션이나 배열과 비교하여, 주어진 모든 컬렉션에 존재하는 키 / 값 쌍을 반환합니다:
$collection = collect([
'color' => 'red',
'size' => 'M',
'material' => 'cotton'
]);
$intersect = $collection->intersectAssoc([
'color' => 'blue',
'size' => 'M',
'material' => 'polyester'
]);
$intersect->all();
// ['size' => 'M']`intersectAssocUsing()` {.collection-method}
intersectAssocUsing 메서드는 원본 컬렉션을 다른 컬렉션이나 배열과 비교하여, 키와 값 모두에 대해 동등성을 판단하는 사용자 정의 콜백을 사용하여 양쪽에 모두 존재하는 키 / 값 쌍을 반환합니다:
$collection = collect([
'color' => 'red',
'Size' => 'M',
'material' => 'cotton',
]);
$intersect = $collection->intersectAssocUsing([
'color' => 'blue',
'size' => 'M',
'material' => 'polyester',
], function (string $a, string $b) {
return strcasecmp($a, $b);
});
$intersect->all();
// ['Size' => 'M']`intersectByKeys()` {.collection-method}
`intersectByKeys` 메서드는 주어진 배열이나 컬렉션에 존재하지 않는 키와 그에 해당하는 값을 원본 컬렉션에서 제거합니다:$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 메서드는 컬렉션이 비어 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다:
collect([])->isEmpty();
// true`isNotEmpty()` {.collection-method}
isNotEmpty 메서드는 컬렉션이 비어 있지 않으면 true를 반환하고, 그렇지 않으면 false를 반환합니다:
collect([])->isNotEmpty();
// false`join()` {.collection-method}
join 메서드는 컬렉션의 값들을 문자열로 결합합니다. 이 메서드의 두 번째 인자를 사용하면 마지막 요소가 문자열에 어떻게 추가될지도 지정할 수 있습니다:
collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
collect(['a'])->join(', ', ' and '); // 'a'
collect([])->join(', ', ' and '); // ''`keyBy()` {.collection-method}
`keyBy` 메서드는 주어진 키를 기준으로 컬렉션의 키를 지정합니다. 여러 항목이 동일한 키를 가지고 있는 경우, 새 컬렉션에는 마지막 항목만 나타납니다:$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'],
]
*/이 메서드에 콜백을 전달할 수도 있습니다. 콜백은 컬렉션의 키로 사용할 값을 반환해야 합니다:
$keyed = $collection->keyBy(function (array $item, int $key) {
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 = 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 메서드는 주어진 진리 검사를 통과하는 컬렉션의 마지막 요소를 반환합니다:
```php
collect([1, 2, 3, 4])->last(function (int $value, int $key) {
return $value < 3;
});
// 2last 메서드를 인자 없이 호출하여 컬렉션의 마지막 요소를 가져올 수도 있습니다. 컬렉션이 비어 있으면 null이 반환됩니다:
collect([1, 2, 3, 4])->last();
// 4`lazy()` {.collection-method}
lazy 메서드는 기본 아이템 배열로부터 새로운 LazyCollection 인스턴스를 반환합니다:
$lazyCollection = collect([1, 2, 3, 4])->lazy();
$lazyCollection::class;
// Illuminate\Support\LazyCollection
$lazyCollection->all();
// [1, 2, 3, 4]이는 많은 아이템을 포함하는 거대한 Collection에 대해 변환 작업을 수행해야 할 때 특히 유용합니다:
$count = $hugeCollection
->lazy()
->where('country', 'FR')
->where('balance', '>', '100')
->count();컬렉션을 LazyCollection으로 변환함으로써, 우리는 많은 추가 메모리를 할당하지 않아도 됩니다. 원래 컬렉션은 여전히 그 자신의 값을 메모리에 유지하지만, 이후의 필터들은 그렇지 않습니다. 따라서 컬렉션 결과를 필터링할 때 사실상 추가 메모리가 거의 할당되지 않습니다.
`macro()` {.collection-method}
정적 메서드인 macro를 사용하면 런타임에 Collection 클래스에 메서드를 추가할 수 있습니다. 더 자세한 내용은 컬렉션 확장하기 문서를 참고하세요.
`make()` {.collection-method}
정적 make 메서드는 새로운 컬렉션 인스턴스를 생성합니다. 컬렉션 생성하기 섹션을 참고하세요.
use Illuminate\Support\Collection;
$collection = Collection::make([1, 2, 3]);`map()` {.collection-method}
map 메서드는 컬렉션을 순회하면서 각 값을 주어진 콜백에 전달합니다. 콜백은 자유롭게 아이템을 수정하고 반환할 수 있으며, 그렇게 수정된 아이템들로 새로운 컬렉션이 만들어집니다:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function (int $item, int $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]WARNING
대부분의 다른 컬렉션 메서드와 마찬가지로, map은 새로운 컬렉션 인스턴스를 반환합니다. 즉, 호출된 원본 컬렉션을 수정하지 않습니다. 원본 컬렉션 자체를 변형하고 싶다면 transform 메서드를 사용하세요.
`mapInto()` {.collection-method}
mapInto() 메서드는 컬렉션을 순회하면서, 값을 생성자에 전달하여 주어진 클래스의 새 인스턴스를 생성합니다:
class Currency
{
/**
* Create a new currency instance.
*/
function __construct(
public string $code,
) {}
}
$collection = collect(['USD', 'EUR', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('USD'), Currency('EUR'), Currency('GBP')]`mapSpread()` {.collection-method}
mapSpread 메서드는 컬렉션의 아이템을 순회하며, 각 중첩된 아이템 값을 주어진 클로저에 전달합니다. 클로저는 자유롭게 아이템을 수정하여 반환할 수 있으며, 이렇게 수정된 아이템들로 새로운 컬렉션이 만들어집니다:
$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunks = $collection->chunk(2);
$sequence = $chunks->mapSpread(function (int $even, int $odd) {
return $even + $odd;
});
$sequence->all();
// [1, 5, 9, 13, 17]`mapToGroups()` {.collection-method}
mapToGroups 메서드는 주어진 클로저를 이용해 컬렉션의 아이템을 그룹화합니다. 이 클로저는 하나의 키 / 값 쌍을 포함하는 연관 배열을 반환해야 하며, 이렇게 그룹화된 값들로 새로운 컬렉션이 만들어집니다:
$collection = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
],
[
'name' => 'Jane Doe',
'department' => 'Sales',
],
[
'name' => 'Johnny Doe',
'department' => 'Marketing',
]
]);
$grouped = $collection->mapToGroups(function (array $item, int $key) {
return [$item['department'] => $item['name']];
});
$grouped->all();
/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']`mapWithKeys()` {.collection-method}
`mapWithKeys` 메서드는 컬렉션을 반복하면서 각 값을 주어진 콜백에 전달합니다. 콜백은 하나의 키 / 값 쌍을 포함하는 연관 배열을 반환해야 합니다:$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com',
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com',
]
]);
$keyed = $collection->mapWithKeys(function (array $item, int $key) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/`max()` {.collection-method}
max 메서드는 주어진 키의 최대값을 반환합니다:
$max = collect([
['foo' => 10],
['foo' => 20]
])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5`median()` {.collection-method}
median 메서드는 주어진 키의 중간값을 반환합니다:
$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 = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]주어진 항목의 키가 숫자인 경우, 값은 컬렉션의 끝에 추가됩니다:
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']`mergeRecursive()` {.collection-method}
mergeRecursive 메서드는 주어진 배열 또는 컬렉션을 원본 컬렉션과 재귀적으로 병합합니다. 주어진 항목의 문자열 키가 원본 컬렉션의 문자열 키와 일치하면, 해당 키들의 값은 배열로 함께 병합되며, 이 작업은 재귀적으로 수행됩니다:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->mergeRecursive([
'product_id' => 2,
'price' => 200,
'discount' => false
]);
$merged->all();
// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]`min()` {.collection-method}
min 메서드는 주어진 키의 최솟값을 반환합니다:
$min = collect([
['foo' => 10],
['foo' => 20]
])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1`mode()` {.collection-method}
mode 메서드는 주어진 키의 최빈값을 반환합니다:
$mode = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->mode('foo');
// [10]
$mode = collect([1, 1, 2, 4])->mode();
// [1]
$mode = collect([1, 1, 2, 2])->mode();
// [1, 2]`multiply()` {.collection-method}
multiply 메서드는 컬렉션에 있는 모든 항목의 지정된 개수만큼 사본을 생성합니다:
$users = collect([
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
])->multiply(3);
/*
[
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
]
*/`nth()` {.collection-method}
nth 메서드는 n번째 요소마다 하나씩 구성된 새 컬렉션을 생성합니다:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
두 번째 인수로 시작 오프셋을 선택적으로 전달할 수도 있습니다:
```php
$collection->nth(4, 1);
// ['b', 'f']`only()` {.collection-method}
only 메서드는 컬렉션에서 지정된 키를 가진 항목들을 반환합니다:
$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 메서드를 참고하세요.
NOTE
이 메서드는 Eloquent 컬렉션을 사용할 때 동작이 변경됩니다.
`pad()` {.collection-method}
pad 메서드는 배열이 지정된 크기에 도달할 때까지 주어진 값으로 배열을 채웁니다. 이 메서드는 PHP의 array_pad 함수처럼 동작합니다.
왼쪽으로 채우려면 음수 크기를 지정하면 됩니다. 주어진 크기의 절댓값이 배열의 길이보다 작거나 같으면 채우기가 이루어지지 않습니다:
$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` 메서드는 PHP 배열 구조 분해(array destructuring)와 결합하여 주어진 진리 테스트를 통과하는 요소와 그렇지 않은 요소를 분리하는 데 사용할 수 있습니다:$collection = collect([1, 2, 3, 4, 5, 6]);
[$underThree, $equalOrAboveThree] = $collection->partition(function (int $i) {
return $i < 3;
});
$underThree->all();
// [1, 2]
$equalOrAboveThree->all();
// [3, 4, 5, 6]NOTE
이 메서드는 Eloquent 컬렉션과 상호작용할 때 동작이 변경됩니다.
`percentage()` {.collection-method}
percentage 메서드는 컬렉션 내에서 주어진 진리 테스트를 통과하는 항목의 비율을 빠르게 확인하는 데 사용할 수 있습니다:
$collection = collect([1, 1, 2, 2, 2, 3]);
$percentage = $collection->percentage(fn (int $value) => $value === 1);
// 33.33기본적으로 비율은 소수점 둘째 자리까지 반올림됩니다. 하지만 메서드에 두 번째 인수를 제공하여 이 동작을 커스터마이징할 수 있습니다:
$percentage = $collection->percentage(fn (int $value) => $value === 1, precision: 3);
// 33.333`pipe()` {.collection-method}
pipe 메서드는 컬렉션을 주어진 클로저에 전달하고 실행된 클로저의 결과를 반환합니다:
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function (Collection $collection) {
return $collection->sum();
});
// 6`pipeInto()` {.collection-method}
pipeInto 메서드는 주어진 클래스의 새 인스턴스를 생성하고 컬렉션을 생성자에 전달합니다:
class ResourceCollection
{
/**
* Create a new ResourceCollection instance.
*/
public function __construct(
public Collection $collection,
) {}
}
$collection = collect([1, 2, 3]);
$resource = $collection->pipeInto(ResourceCollection::class);
$resource->collection->all();
// [1, 2, 3]`pipeThrough()` {.collection-method}
pipeThrough 메서드는 주어진 클로저 배열에 컬렉션을 전달하고 실행된 클로저의 결과를 반환합니다:
use Illuminate\Support\Collection;
$collection = collect([1, 2, 3]);
$result = $collection->pipeThrough([
function (Collection $collection) {
return $collection->merge([4, 5]);
},
function (Collection $collection) {
return $collection->sum();
},
]);
// 15`pluck()` {.collection-method}
pluck 메서드는 주어진 키에 대한 모든 값을 조회합니다:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']결과 컬렉션의 키를 어떻게 지정할지도 정할 수 있습니다:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
`pluck` 메서드는 "dot" 표기법을 사용하여 중첩된 값을 조회하는 것도 지원합니다:
```php
$collection = collect([
[
'name' => 'Laracon',
'speakers' => [
'first_day' => ['Rosa', 'Judith'],
],
],
[
'name' => 'VueConf',
'speakers' => [
'first_day' => ['Abigail', 'Joey'],
],
],
]);
$plucked = $collection->pluck('speakers.first_day');
$plucked->all();
// [['Rosa', 'Judith'], ['Abigail', 'Joey']]중복된 키가 존재하는 경우, 마지막으로 일치하는 요소가 pluck된 컬렉션에 삽입됩니다:
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']`pop()` {.collection-method}
pop 메서드는 컬렉션의 마지막 아이템을 제거하고 반환합니다. 컬렉션이 비어 있다면, null이 반환됩니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]pop 메서드에 정수를 전달하면 컬렉션의 끝에서 여러 개의 아이템을 제거하고 반환할 수 있습니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop(3);
// collect([5, 4, 3])
$collection->all();
// [1, 2]`prepend()` {.collection-method}
prepend 메서드는 컬렉션의 맨 앞에 항목을 추가합니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]추가되는 항목의 키를 지정하기 위해 두 번째 인수를 전달할 수도 있습니다:
$collection = collect(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]`pull()` {.collection-method}
pull 메서드는 컬렉션에서 키를 기준으로 항목을 제거하고 반환합니다:
$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']`push()` {.collection-method}
push 메서드는 컬렉션의 끝에 항목을 추가합니다:
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]컬렉션의 끝에 추가할 여러 개의 항목을 함께 전달할 수도 있습니다:
$collection = collect([1, 2, 3, 4]);
$collection->push(5, 6, 7);
$collection->all();
// [1, 2, 3, 4, 5, 6, 7]`put()` {.collection-method}
put 메서드는 컬렉션에 주어진 키와 값을 설정합니다:
$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 = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (임의로 조회됨)random에 정수를 전달하여 임의로 조회하고 싶은 아이템의 개수를 지정할 수 있습니다. 조회하고자 하는 아이템의 개수를 명시적으로 전달하면 항상 아이템들의 컬렉션이 반환됩니다:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (임의로 조회됨)컬렉션 인스턴스에 요청한 것보다 적은 아이템이 있는 경우, random 메서드는 InvalidArgumentException을 발생시킵니다.
random 메서드는 클로저도 받을 수 있으며, 이 클로저는 현재 컬렉션 인스턴스를 전달받습니다:
use Illuminate\Support\Collection;
$random = $collection->random(fn (Collection $items) => min(10, count($items)));
$random->all();
// [1, 2, 3, 4, 5] - (임의로 조회됨)`range()` {.collection-method}
range 메서드는 지정된 범위 사이의 정수를 포함하는 컬렉션을 반환합니다:
$collection = collect()->range(3, 6);
$collection->all();
// [3, 4, 5, 6]`reduce()` {.collection-method}
```php $collection = collect([1, 2, 3]);$total = $collection->reduce(function (?int $carry, int $item) { return $carry + $item; });
// 6
`reduce` 메서드는 컬렉션을 단일 값으로 줄이며, 각 반복의 결과를 다음 반복으로 전달합니다:
첫 번째 반복에서 `$carry`의 값은 `null`입니다. 하지만 `reduce`에 두 번째 인수를 전달하여 초기값을 지정할 수 있습니다:
```php
$collection->reduce(function (int $carry, int $item) {
return $carry + $item;
}, 4);
// 10reduce 메서드는 배열 키도 주어진 콜백에 전달합니다:
$collection = collect([
'usd' => 1400,
'gbp' => 1200,
'eur' => 1000,
]);
$ratio = [
'usd' => 1,
'gbp' => 1.37,
'eur' => 1.22,
];
$collection->reduce(function (int $carry, int $value, string $key) use ($ratio) {
return $carry + ($value * $ratio[$key]);
}, 0);
// 4264`reduceInto()` {.collection-method}
reduceInto 메서드는 주어진 초기값을 변경(mutate)하여 컬렉션을 단일 값으로 줄입니다. reduce 메서드와 달리, 주어진 콜백은 누적된 값을 반환할 필요가 없습니다:
class OrderStats
{
public int $total = 0;
public int $count = 0;
}
$orders = collect([
['amount' => 100],
['amount' => 250],
['amount' => 50],
]);
$stats = $orders->reduceInto(new OrderStats, function (OrderStats $stats, array $order) {
$stats->total += $order['amount'];
$stats->count++;
});
$stats->total;
// 400스칼라나 배열로 리듀스할 때는 콜백에서 참조로 값을 받아야 변경 사항이 원본 값에 적용됩니다:
$collection = collect([1, 2, 3, 4, 5]);
$even = $collection->reduceInto([], function (array &$result, int $value) {
if ($value % 2 === 0) {
$result[] = $value;
}
});
// [2, 4]`reduceSpread()` {.collection-method}
reduceSpread 메서드는 컬렉션을 값의 배열로 리듀스하며, 각 반복(iteration)의 결과를 다음 반복으로 전달합니다. 이 메서드는 reduce 메서드와 유사하지만, 여러 개의 초기값을 받을 수 있습니다:
[$creditsRemaining, $batch] = Image::where('status', 'unprocessed')
->get()
->reduceSpread(function (int $creditsRemaining, Collection $batch, Image $image) {
if ($creditsRemaining >= $image->creditsRequired()) {
$batch->push($image);
$creditsRemaining -= $image->creditsRequired();
}
return [$creditsRemaining, $batch];
}, $creditsAvailable, collect());`reject()` {.collection-method}
reject 메서드는 주어진 클로저를 사용하여 컬렉션을 필터링합니다. 클로저는 결과 컬렉션에서 해당 항목을 제거해야 할 경우 true를 반환해야 합니다:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function (int $value, int $key) {
```php
return $value > 2;
});
$filtered->all();
// [1, 2]reject 메서드의 반대 동작에 대해서는 filter 메서드를 참고하세요.
`replace()` {.collection-method}
replace 메서드는 merge와 비슷하게 동작합니다. 하지만 문자열 키를 가진 일치하는 항목을 덮어쓰는 것 외에도, replace 메서드는 숫자 키가 일치하는 컬렉션의 항목도 덮어씁니다:
$collection = collect(['Taylor', 'Abigail', 'James']);
$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);
$replaced->all();
// ['Taylor', 'Victoria', 'James', 'Finn']`replaceRecursive()` {.collection-method}
replaceRecursive 메서드는 replace와 비슷하게 동작하지만, 배열 내부까지 재귀적으로 탐색하여 내부 값에도 동일한 대체 과정을 적용합니다:
$collection = collect([
'Taylor',
'Abigail',
[
'James',
'Victoria',
'Finn'
]
]);
$replaced = $collection->replaceRecursive([
'Charlie',
2 => [1 => 'King']
]);
$replaced->all();
// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]`reverse()` {.collection-method}
reverse 메서드는 컬렉션 항목의 순서를 뒤집으며, 기존 키는 그대로 유지합니다:
$collection = collect(['a', 'b', 'c', 'd', 'e']);
$reversed = $collection->reverse();
$reversed->all();
/*
[
4 => 'e',
3 => 'd',
```php
2 => 'c',
1 => 'b',
0 => 'a',
]
*/`search()` {.collection-method}
search 메서드는 컬렉션에서 주어진 값을 검색하여 발견되면 해당 키를 반환합니다. 아이템을 찾지 못하면 false가 반환됩니다:
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1검색은 "느슨한(loose)" 비교로 수행되며, 이는 정수 값을 가진 문자열이 동일한 값의 정수와 같은 것으로 간주됨을 의미합니다. "엄격한(strict)" 비교를 사용하려면 메서드의 두 번째 인수로 true를 전달하세요:
collect([2, 4, 6, 8])->search('4', strict: true);
// false또는 주어진 진리 테스트를 통과하는 첫 번째 아이템을 검색하기 위해 자신만의 클로저를 제공할 수도 있습니다:
collect([2, 4, 6, 8])->search(function (int $item, int $key) {
return $item > 5;
});
// 2`select()` {.collection-method}
select 메서드는 SQL의 SELECT 구문과 유사하게 컬렉션에서 주어진 키들을 선택합니다:
$users = collect([
['name' => 'Taylor Otwell', 'role' => 'Developer', 'status' => 'active'],
['name' => 'Victoria Faith', 'role' => 'Researcher', 'status' => 'active'],
]);
$users->select(['name', 'role']);
/*
[
['name' => 'Taylor Otwell', 'role' => 'Developer'],
['name' => 'Victoria Faith', 'role' => 'Researcher'],
],
*/`shift()` {.collection-method}
$subset->all();// [3, 4]
You may also pass a simple value to the `skipUntil` method to skip all items until the given value is found:
```php
$collection = collect([1, 2, 3, 4]);
$subset = $collection->skipUntil(3);
$subset->all();
// [3, 4]WARNING
If the given value is not found or the callback never returns true, the skipUntil method will return an empty collection.
`skipWhile()` {.collection-method}
The skipWhile method skips over items from the collection while the given callback returns true and returns the remaining items in the collection as a new collection once the callback returns false:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->skipWhile(function (int $item) {
return $item <= 3;
});
$subset->all();
// [4]WARNING
If the callback never returns false, the skipWhile method will return an empty collection.
`slice()` {.collection-method}
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]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]The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the values method to reindex them.
`sliding()` {.collection-method}
The sliding method returns a new collection of chunks representing a "sliding window" view of the items in the collection:
$collection = collect([1, 2, 3, 4, 5]);
$chunks = $collection->sliding(2);
$chunks->toArray();
// [[1, 2], [2, 3], [3, 4], [4, 5]]This is especially useful in conjunction with the eachSpread method:
$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) {
$current->total = $previous->total + $current->amount;
});You may optionally pass a second "step" value, which determines the distance between the first item of every chunk:
$collection = collect([1, 2, 3, 4, 5]);
$chunks = $collection->sliding(3, step: 2);
$chunks->toArray();
// [[1, 2, 3], [3, 4, 5]]sole() {.collection-method}
The sole method returns the first element in the collection that passes a given truth test, but only if the truth test matches exactly one element:
collect([1, 2, 3, 4])->sole(function (int $value) {
return $value === 2;
});
// 2You may also pass a key / value pair to the sole method, which will return the first element in the collection that matches the given pair, but only if it exactly one element matches:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->sole('product', 'Chair');
// ['product' => 'Chair', 'price' => 100]Alternatively, you may also call the sole method with no arguments to get the first element in the collection if there is only one element:
$collection = collect([
['product' => 'Desk', 'price' => 200],
]);
$collection->sole();
// ['product' => 'Desk', 'price' => 200]If there are no elements in the collection that should be returned by the sole method, an \Illuminate\Collections\ItemNotFoundException exception will be thrown. If there is more than one element that should be returned, an \Illuminate\Collections\MultipleItemsFoundException will be thrown.
some() {.collection-method}
Alias for the contains method.
sort() {.collection-method}
The sort method sorts the collection. The sorted collection keeps the original array keys, so in the following example we will use the 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]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, which is what the collection's sort method calls under the hood.
NOTE
If you need to sort a collection of nested arrays or objects, see the sortBy and sortByDesc methods.
sortBy() {.collection-method}
The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in the following example we will use the 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],
]
*/The sortBy method accepts sort flags as its second argument:
$collection = collect([
['title' => 'Item 1'],
['title' => 'Item 12'],
['title' => 'Item 3'],
]);
$sorted = $collection->sortBy('title', SORT_NATURAL);
$sorted->values()->all();
/*
[
['title' => 'Item 1'],
['title' => 'Item 3'],
['title' => 'Item 12'],
]
*/Alternatively, you may pass your own closure to determine how to sort the collection's values:
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function (array $product, int $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/If you would like to sort your collection by multiple attributes, you may pass an array of sort operations to the sortBy method. Each sort operation should be an array consisting of the attribute and direction of the sort:
$collection = collect([
['name' => 'Taylor Otwell', 'age' => 34],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Abigail Otwell', 'age' => 32],
]);
$sorted = $collection->sortBy([
['name', 'asc'],
['age', 'desc'],
]);
$sorted->values()->all();
/*
[
['name' => 'Abigail Otwell', 'age' => 32],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Taylor Otwell', 'age' => 34],
]
*/When sorting a collection by multiple attributes, you may also provide closures that define each sort operation:
$collection = collect([
['name' => 'Taylor Otwell', 'age' => 34],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Abigail Otwell', 'age' => 32],
]);
$sorted = $collection->sortBy([
fn (array $a, array $b) => $a['name'] <=> $b['name'],
fn (array $a, array $b) => $b['age'] <=> $a['age'],
]);
$sorted->values()->all();
/*
[
['name' => 'Abigail Otwell', 'age' => 32],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Taylor Otwell', 'age' => 34],
]
*/sortByDesc() {.collection-method}
This method has the same signature as the sortBy method, but will sort the collection in the opposite order.
sortDesc() {.collection-method}
This method will sort the collection in the opposite order as the sort method:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sortDesc();
$sorted->values()->all();
// [5, 4, 3, 2, 1]Unlike sort, you may not pass a closure to sortDesc. Instead, you should use the sort method and invert your comparison.
sortKeys() {.collection-method}
The sortKeys method sorts the collection by the keys of the underlying associative array:
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/sortKeysDesc() {.collection-method}
This method has the same signature as the sortKeys method, but will sort the collection in the opposite order.
sortKeysUsing() {.collection-method}
The sortKeysUsing method sorts the collection by the keys of the underlying associative array using a callback:
$collection = collect([
'ID' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeysUsing('strnatcasecmp');
$sorted->all();
/*
[
'first' => 'John',
'ID' => 22345,
'last' => 'Doe',
]
*/The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on uksort, which is the PHP function that sortKeysUsing method utilizes internally.
splice() {.collection-method}
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]You may pass a second argument to limit the size of the resulting collection:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]In addition, you may 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}
The split method breaks a collection into the given number of groups:
$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->all();
// [[1, 2], [3, 4], [5]]splitIn() {.collection-method}
The splitIn method breaks a collection into the given number of groups, filling non-terminal groups completely before allocating the remainder to the final group:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$groups = $collection->splitIn(3);
$groups->all();
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]sum() {.collection-method}
The sum method returns the sum of all items in the collection:
collect([1, 2, 3, 4, 5])->sum();
// 15If the collection contains nested arrays or objects, you should pass a key that will be used to determine which values to sum:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272In addition, you may pass your own closure 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 (array $product) {
return count($product['colors']);
});
// 6take() {.collection-method}
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 number of items from the end of the collection:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]takeUntil() {.collection-method}
The takeUntil method returns items in the collection until the given callback returns true:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeUntil(function (int $item) {
return $item >= 3;
});
$subset->all();
// [1, 2]You may also pass a simple value to the takeUntil method to get the items until the given value is found:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeUntil(3);
$subset->all();
// [1, 2]WARNING
If the given value is not found or the callback never returns true, the takeUntil method will return all items in the collection.
takeWhile() {.collection-method}
The takeWhile method returns items in the collection until the given callback returns false:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeWhile(function (int $item) {
return $item < 3;
});
$subset->all();
// [1, 2]WARNING
If the callback never returns false, the takeWhile method will return all items in the collection.
tap() {.collection-method}
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 $collection) {
Log::debug('Values after sorting', $collection->values()->all());
})
->shift();
// 1times() {.collection-method}
The static times method creates a new collection by invoking the given closure a specified number of times:
$collection = Collection::times(10, function (int $number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]toArray() {.collection-method}
The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/WARNING
toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw array underlying the collection, use the all method instead.
toJson() {.collection-method}
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}
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 (int $item, int $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]WARNING
Unlike most other collection methods, transform modifies the collection itself. If you wish to create a new collection instead, use the map method.
undot() {.collection-method}
The undot method expands a single-dimensional collection that uses "dot" notation into a multi-dimensional collection:
$person = collect([
'name.first' => 'Marie',
'name.last' => 'Valentine',
'address.line_1' => '2992 Eagle Drive',
'address.line_2' => '',
'address.suburb' => 'Detroit',
'address.state' => 'MI',
'address.postcode' => '48219'
]);
$person = $person->undot();
$person->toArray();
/*
[
"name" => [
"first" => "Marie",
"last" => "Valentine",
],
"address" => [
"line_1" => "2992 Eagle Drive",
"line_2" => "",
"suburb" => "Detroit",
"state" => "MI",
"postcode" => "48219",
],
]
*/union() {.collection-method}
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 => ['d']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]unique() {.collection-method}
The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in the following example we will use the 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'],
]
*/Finally, you may also pass your own closure to the unique method to specify which value should determine an item's uniqueness:
$unique = $collection->unique(function (array $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'],
]
*/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 to filter using "strict" comparisons.
NOTE
This method's behavior is modified when using Eloquent Collections.
uniqueStrict() {.collection-method}
This method has the same signature as the unique method; however, all values are compared using "strict" comparisons.
unless() {.collection-method}
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 $collection) {
return $collection->push(4);
});
$collection->all();
// [1, 2, 3]
$collection->unless(false, function (Collection $collection) {
return $collection->push(4);
});
$collection->all();
// [1, 2, 3, 4]A second callback may be passed to the unless method. The second callback will be executed when the first argument given to the unless method evaluates to true:
$collection = collect([1, 2, 3]);
$collection->unless(true, function (Collection $collection) {
return $collection->push(4);
}, function (Collection $collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]For the inverse of unless, see the when method.
unwrap() {.collection-method}
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'value() {.collection-method}
The value method retrieves a given value from the first element of the collection:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Desk', 'price' => 200],
]);
$value = $collection->value('price');
// 200values() {.collection-method}
The values method returns a new collection with the keys reset to consecutive integers, starting from zero:
$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],
]
*/$subset->all();
// [3, 4]skipUntil 메서드에 단순한 값을 전달하여 주어진 값이 발견될 때까지 모든 항목을 건너뛸 수도 있습니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->skipUntil(3);
$subset->all();
// [3, 4]WARNING
주어진 값을 찾지 못하거나 콜백이 true를 반환하지 않는 경우, skipUntil 메서드는 빈 컬렉션을 반환합니다.
skipWhile() {.collection-method}
skipWhile 메서드는 주어진 콜백이 true를 반환하는 동안 컬렉션의 항목들을 건너뜁니다. 콜백이 false를 반환하면 컬렉션에 남아있는 모든 항목이 새 컬렉션으로 반환됩니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->skipWhile(function (int $item) {
return $item <= 3;
});
$subset->all();
// [4]WARNING
콜백이 false를 반환하지 않으면, skipWhile 메서드는 빈 컬렉션을 반환합니다.
slice() {.collection-method}
slice 메서드는 주어진 인덱스부터 시작하는 컬렉션의 일부분을 반환합니다:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]반환되는 슬라이스의 크기를 제한하고 싶다면, 원하는 크기를 두 번째 인수로 메서드에 전달하십시오:
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]sliding() {.collection-method}
sliding 메서드는 컬렉션 내 아이템들의 "슬라이딩 윈도우" 뷰를 나타내는 청크로 이루어진 새로운 컬렉션을 반환합니다:
$collection = collect([1, 2, 3, 4, 5]);
$chunks = $collection->sliding(2);
$chunks->toArray();
// [[1, 2], [2, 3], [3, 4], [4, 5]]이는 eachSpread 메서드와 함께 사용할 때 특히 유용합니다:
$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) {
$current->total = $previous->total + $current->amount;
});선택적으로 두 번째 "step" 값을 전달할 수 있는데, 이는 각 청크의 첫 번째 아이템 사이의 거리를 결정합니다:
$collection = collect([1, 2, 3, 4, 5]);
$chunks = $collection->sliding(3, step: 2);
$chunks->toArray();
// [[1, 2, 3], [3, 4, 5]]sole() {.collection-method}
sole 메서드는 주어진 진리 테스트를 통과하는 컬렉션의 첫 번째 요소를 반환하는데, 단 그 진리 테스트를 정확히 하나의 요소만 통과할 경우에 한합니다:
collect([1, 2, 3, 4])->sole(function (int $value, int $key) {
return $value === 2;
});
// 2sole 메서드에 key / value 쌍을 전달할 수도 있으며, 이 경우 주어진 쌍과 일치하는 요소가 정확히 하나만 있을 때 그 요소를 반환합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->sole('product', 'Chair');
// ['product' => 'Chair', 'price' => 100]또한 인자 없이 sole 메서드를 호출하여 컬렉션에 요소가 하나뿐일 경우 그 첫 번째 요소를 가져올 수도 있습니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
]);
$collection->sole();
// ['product' => 'Desk', 'price' => 200]sole 메서드가 반환해야 할 요소가 컬렉션에 하나도 없으면 \Illuminate\Collections\ItemNotFoundException 예외가 발생합니다. 반환해야 할 요소가 하나보다 많으면 \Illuminate\Collections\MultipleItemsFoundException 예외가 발생합니다.
some() {.collection-method}
contains 메서드의 별칭입니다.
sort() {.collection-method}
sort 메서드는 컬렉션을 정렬합니다. 정렬된 컬렉션은 원래의 배열 키를 그대로 유지하므로, 다음 예제에서는 키를 연속된 숫자 인덱스로 재설정하기 위해 values 메서드를 사용합니다:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]더 복잡한 정렬이 필요하다면, 자신만의 알고리즘으로 콜백을 sort에 전달할 수 있습니다. 컬렉션의 sort 메서드가 내부적으로 활용하는 PHP의 uasort 문서를 참고하세요.
NOTE
중첩된 배열이나 객체로 이루어진 컬렉션을 정렬해야 한다면, sortBy와 sortByDesc 메서드를 참고하세요.
sortBy() {.collection-method}
sortBy 메서드는 주어진 키를 기준으로 컬렉션을 정렬합니다. 정렬된 컬렉션은 원본 배열의 키를 그대로 유지하므로, 다음 예제에서는 values 메서드를 사용하여 키를 연속된 숫자 인덱스로 재설정합니다:
$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],
]
*/sortBy 메서드는 두 번째 인자로 정렬 플래그를 받을 수 있습니다:
$collection = collect([
['title' => 'Item 1'],
['title' => 'Item 12'],
['title' => 'Item 3'],
]);
$sorted = $collection->sortBy('title', SORT_NATURAL);
$sorted->values()->all();
/*
[
['title' => 'Item 1'],
['title' => 'Item 3'],
['title' => 'Item 12'],
]
*/컬렉션 값을 어떻게 정렬할지 결정하기 위해 직접 클로저를 전달할 수도 있습니다:
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function (array $product, int $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/여러 속성을 기준으로 컬렉션을 정렬하고 싶다면, sortBy 메서드에 정렬 작업의 배열을 전달할 수 있습니다. 각 정렬 작업은 정렬하고자 하는 속성과 원하는 정렬 방향으로 구성된 배열이어야 합니다:
$collection = collect([
['name' => 'Taylor Otwell', 'age' => 34],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Abigail Otwell', 'age' => 32],
]);
$sorted = $collection->sortBy([
['name', 'asc'],
['age', 'desc'],
]);
$sorted->values()->all();
/*
[
['name' => 'Abigail Otwell', 'age' => 32],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Taylor Otwell', 'age' => 34],
]
*/컬렉션을 여러 속성으로 정렬할 때, 각 정렬 작업을 정의하는 클로저를 제공할 수도 있습니다.
$collection = collect([
['name' => 'Taylor Otwell', 'age' => 34],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Abigail Otwell', 'age' => 32],
]);
$sorted = $collection->sortBy([
fn (array $a, array $b) => $a['name'] <=> $b['name'],
fn (array $a, array $b) => $b['age'] <=> $a['age'],
]);
$sorted->values()->all();
/*
[
['name' => 'Abigail Otwell', 'age' => 32],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Taylor Otwell', 'age' => 34],
]
*/sortByDesc() {.collection-method}
이 메서드는 sortBy 메서드와 동일한 시그니처를 가지고 있지만, 컬렉션을 반대 순서로 정렬합니다.
sortDesc() {.collection-method}
이 메서드는 sort 메서드와 반대 순서로 컬렉션을 정렬합니다.
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sortDesc();
$sorted->values()->all();
// [5, 4, 3, 2, 1]sort와 달리, sortDesc에는 클로저를 전달할 수 없습니다. 대신 sort 메서드를 사용하고 비교 로직을 반전시켜야 합니다.
sortKeys() {.collection-method}
sortKeys 메서드는 기본 연관 배열의 키를 기준으로 컬렉션을 정렬합니다:
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/sortKeysDesc() {.collection-method}
이 메서드는 sortKeys 메서드와 시그니처가 동일하지만, 컬렉션을 반대 순서로 정렬합니다.
sortKeysUsing() {.collection-method}
sortKeysUsing 메서드는 콜백을 사용하여 기본 연관 배열의 키를 기준으로 컬렉션을 정렬합니다:
$collection = collect([
'ID' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeysUsing('strnatcasecmp');
$sorted->all();
/*
[
'first' => 'John',
'ID' => 22345,
'last' => 'Doe',
]
*/콜백은 0보다 작거나, 같거나, 큰 정수를 반환하는 비교 함수여야 합니다. 자세한 내용은 sortKeysUsing 메서드가 내부적으로 사용하는 PHP 함수인 uksort에 대한 PHP 문서를 참고하세요.
splice() {.collection-method}
splice 메서드는 지정된 인덱스부터 시작하는 항목의 일부를 제거하고 반환합니다:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]결과 컬렉션의 크기를 제한하기 위해 두 번째 인수를 전달할 수 있습니다:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]또한, 컬렉션에서 제거된 항목을 대체할 새로운 항목을 담은 세 번째 인수를 전달할 수 있습니다:
$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 = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->all();
// [[1, 2], [3, 4], [5]]splitIn() {.collection-method}
splitIn 메서드는 컬렉션을 주어진 개수의 그룹으로 나누며, 마지막 그룹에 나머지를 할당하기 전에 마지막이 아닌 그룹들을 완전히 채웁니다:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$groups = $collection->splitIn(3);
$groups->all();
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]sum() {.collection-method}
sum 메서드는 컬렉션에 있는 모든 아이템의 합계를 반환합니다:
collect([1, 2, 3, 4, 5])->sum();
// 15컬렉션에 중첩 배열이나 객체가 포함된 경우, 어떤 값을 합산할지 결정하는 데 사용할 키를 전달해야 합니다:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272또한, 컬렉션에서 어떤 값을 합산할지 결정하기 위해 직접 클로저를 전달할 수도 있습니다:
$collection = collect([
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function (array $product) {
return count($product['colors']);
});
// 6take() {.collection-method}
take 메서드는 지정된 개수의 아이템을 가진 새로운 컬렉션을 반환합니다:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]또한 음수를 전달하여 컬렉션의 끝에서부터 지정된 개수의 아이템을 가져올 수도 있습니다:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]takeUntil() {.collection-method}
takeUntil 메서드는 주어진 콜백이 true를 반환할 때까지 컬렉션의 항목을 반환합니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeUntil(function (int $item) {
return $item >= 3;
});
$subset->all();
// [1, 2]takeUntil 메서드에 단순한 값을 전달하여 주어진 값을 찾을 때까지의 항목을 얻을 수도 있습니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeUntil(3);
$subset->all();
// [1, 2]WARNING
주어진 값을 찾을 수 없거나 콜백이 true를 반환하지 않는 경우, takeUntil 메서드는 컬렉션의 모든 항목을 반환합니다.
takeWhile() {.collection-method}
takeWhile 메서드는 주어진 콜백이 false를 반환할 때까지 컬렉션의 항목을 반환합니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeWhile(function (int $item) {
return $item < 3;
});
$subset->all();
// [1, 2]WARNING
콜백이 false를 반환하지 않는 경우, takeWhile 메서드는 컬렉션의 모든 항목을 반환합니다.
tap() {.collection-method}
tap 메서드는 주어진 콜백에 컬렉션을 전달하여, 컬렉션 자체에 영향을 주지 않으면서 특정 시점에 컬렉션을 "탭(tap)"하여 항목으로 무언가를 할 수 있도록 해줍니다. 그런 다음 tap 메서드는 해당 컬렉션을 반환합니다:
collect([2, 4, 3, 1, 5])
->sort()
->tap(function (Collection $collection) { Log::debug('Values after sorting', $collection->values()->all());
})
->shift();// 1
#### `times()` {.collection-method}
정적 `times` 메서드는 주어진 클로저를 지정된 횟수만큼 호출하여 새로운 컬렉션을 생성합니다:
```php
$collection = Collection::times(10, function (int $number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]toArray() {.collection-method}
toArray 메서드는 컬렉션을 순수한 PHP array로 변환합니다. 컬렉션의 값이 Eloquent 모델인 경우, 해당 모델들도 배열로 변환됩니다:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/WARNING
toArray는 컬렉션에 중첩된 Arrayable의 인스턴스인 객체들도 모두 배열로 변환합니다. 컬렉션의 원본 배열을 그대로 가져오고 싶다면 대신 all 메서드를 사용하세요.
toJson() {.collection-method}
toJson 메서드는 컬렉션을 JSON으로 직렬화된 문자열로 변환합니다:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk", "price":200}'toPrettyJson() {.collection-method}
toPrettyJson 메서드는 JSON_PRETTY_PRINT 옵션을 사용하여 컬렉션을 포맷된 JSON 문자열로 변환합니다:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toPrettyJson();transform() {.collection-method}
transform 메서드는 컬렉션을 반복하면서 컬렉션의 각 항목과 함께 주어진 콜백을 호출합니다. 컬렉션의 항목들은 콜백이 반환하는 값으로 대체됩니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function (int $item, int $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]WARNING
대부분의 다른 컬렉션 메서드와 달리, transform은 컬렉션 자체를 수정합니다. 대신 새로운 컬렉션을 생성하고 싶다면 map 메서드를 사용하세요.
undot() {.collection-method}
undot 메서드는 "점(dot)" 표기법을 사용하는 1차원 컬렉션을 다차원 컬렉션으로 확장합니다:
$person = collect([
'name.first_name' => 'Marie',
'name.last_name' => 'Valentine',
'address.line_1' => '2992 Eagle Drive',
'address.line_2' => '',
'address.suburb' => 'Detroit',
'address.state' => 'MI',
'address.postcode' => '48219'
]);
$person = $person->undot();
$person->toArray();
/*
[
"name" => [
"first_name" => "Marie",
"last_name" => "Valentine",
],
"address" => [
['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'],
]
*/Finally, you may also pass your own closure to the unique method to specify which value should determine an item's 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'],
]
*/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 to filter using "strict" comparisons.
NOTE
This method's behavior is modified when using Eloquent Collections.
uniqueStrict() {.collection-method}
This method has the same signature as the unique method; however, all values are compared using "strict" comparisons.
unless() {.collection-method}
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 $collection) {
return $collection->push(4);
});
$collection->unless(false, function (Collection $collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]A second callback may be passed to the unless method. The second callback will be executed when the first argument given to the unless method evaluates to true:
$collection = collect([1, 2, 3]);
$collection->unless(true, function (Collection $collection) {
return $collection->push(4);
}, function (Collection $collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]For the inverse of unless, see the when method.
unlessEmpty() {.collection-method}
Alias for the whenNotEmpty method.
unlessNotEmpty() {.collection-method}
Alias for the whenEmpty method.
unwrap() {.collection-method}
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'value() {.collection-method}
The value method retrieves a given value from the first element of the collection:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Speaker', 'price' => 400],
]);
$value = $collection->value('price');
// 200values() {.collection-method}
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}
The when method will execute the given callback when the first argument given to the method evaluates to true. The collection instance and the first argument given to the when method will be provided to the closure:
$collection = collect([1, 2, 3]);
$collection->when(true, function (Collection $collection, int $value) {
return $collection->push(4);
});
$collection->all();
// [1, 2, 3, 4]A second callback may be passed to the when method. The second callback will be executed when the first argument given to the when method evaluates to false:
$collection = collect([1, 2, 3]);
$collection->when(false, function (Collection $collection, int $value) {
return $collection->push(4);
}, function (Collection $collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]For the inverse of when, see the unless method.
whenEmpty() {.collection-method}
The whenEmpty method will execute the given callback when the collection is empty:
$collection = collect(['Michael', 'Tom']);
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Adam');
});
$collection->all();
// ['Michael', 'Tom']$collection = collect();
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Adam');
});
$collection->all();
// ['Adam']A second closure may be passed to the whenEmpty method that will be executed when the collection is not empty:
$collection = collect(['Michael', 'Tom']);
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Adam');
}, function (Collection $collection) {
return $collection->push('Taylor');
});
$collection->all();
// ['Michael', 'Tom', 'Taylor']For the inverse of whenEmpty, see the whenNotEmpty method.
whenNotEmpty() {.collection-method}
The whenNotEmpty method will execute the given callback when the collection is not empty:
$collection = collect(['michael', 'tom']);
$collection->whenNotEmpty(function (Collection $collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom', 'adam']$collection = collect();
$collection->whenNotEmpty(function (Collection $collection) {
return $collection->push('adam');
});
$collection->all();
// []A second closure may be passed to the whenNotEmpty method that will be executed when the collection is empty:
$collection = collect();
$collection->whenNotEmpty(function (Collection $collection) {
return $collection->push('adam');
}, function (Collection $collection) {
return $collection->push('taylor');
});
$collection->all();
// ['taylor']For the inverse of whenNotEmpty, see the whenEmpty method.
where() {.collection-method}
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],
]
*/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 to filter using "strict" comparisons.
Optionally, you may pass a comparison operator as the second parameter. Supported operators are: '===', '!==', '!=', '==', '=', '<>', '>', '<', '>=', and '<='.
$collection = collect([
['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
['name' => 'Sue', 'deleted_at' => null],
]);
$filtered = $collection->where('deleted_at', '!=', null);
$filtered->all();
/*
[
['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
]
*/whereStrict() {.collection-method}
This method has the same signature as the where method; however, all values are compared using "strict" comparisons.
whereBetween() {.collection-method}
The whereBetween method filters the collection by determining if a specified item value is within a given range:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]
*/whereIn() {.collection-method}
The whereIn method removes elements from the collection that do not have a specified item value that is 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' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
]
*/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 to filter using "strict" comparisons.
whereInStrict() {.collection-method}
This method has the same signature as the whereIn method; however, all values are compared using "strict" comparisons.
whereInstanceOf() {.collection-method}
The whereInstanceOf method filters the collection by a given class type:
use App\Models\User;
use App\Models\Post;
$collection = collect([
new User,
new Post,
]);
$filtered = $collection->whereInstanceOf(User::class);
$filtered->all();
// [App\Models\User]whereNotBetween() {.collection-method}
The whereNotBetween method filters the collection by determining if a specified item value is outside of a given range:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 80],
['product' => 'Pencil', 'price' => 30],
]
*/whereNotIn() {.collection-method}
The whereNotIn method removes elements from the collection that have a specified item value that is 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],
]
*/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 to filter using "strict" comparisons.
whereNotInStrict() {.collection-method}
This method has the same signature as the whereNotIn method; however, all values are compared using "strict" comparisons.
whereNotNull() {.collection-method}
The whereNotNull method returns items from the collection where the given key is not null:
$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNotNull('name');
$filtered->all();
/*
[
['name' => 'Desk'],
['name' => 'Bookcase'],
]
*/whereNull() {.collection-method}
The whereNull method returns items from the collection where the given key is null:
$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNull('name');
$filtered->all();
/*
[
['name' => null],
]
*/wrap() {.collection-method}
The static wrap method wraps the given value in a collection when applicable:
use Illuminate\Support\Collection;
$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']['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'], ] */
마지막으로, 항목의 고유성을 판단할 값을 지정하기 위해 직접 클로저를 `unique` 메서드에 전달할 수도 있습니다:
```php
$unique = $collection->unique(function (array $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 메서드는 항목 값을 확인할 때 "느슨한(loose)" 비교를 사용합니다. 즉, 정수 값을 가진 문자열은 동일한 값을 가진 정수와 같은 것으로 취급됩니다. "엄격한(strict)" 비교를 사용하여 필터링하려면 uniqueStrict 메서드를 사용하세요.
NOTE
이 메서드의 동작은 Eloquent 컬렉션을 사용할 때 변경됩니다.
uniqueStrict() {.collection-method}
이 메서드는 unique 메서드와 시그니처가 동일합니다. 다만 모든 값이 "엄격한(strict)" 비교 방식으로 비교됩니다.
unless() {.collection-method}
unless 메서드는 메서드에 전달된 첫 번째 인수가 true로 평가되지 않는 한 주어진 콜백을 실행합니다. 컬렉션 인스턴스와 unless 메서드에 전달된 첫 번째 인수가 클로저에 제공됩니다:
$collection = collect([1, 2, 3]);
$collection->unless(true, function (Collection $collection, bool $value) {
return $collection->push(4);
});
$collection->unless(false, function (Collection $collection, bool $value) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]unless 메서드에는 두 번째 콜백을 전달할 수도 있습니다. 두 번째 콜백은 unless 메서드에 전달된 첫 번째 인수가 true로 평가될 때 실행됩니다:
$collection = collect([1, 2, 3]);
$collection->unless(true, function (Collection $collection, bool $value) {
return $collection->push(4);
}, function (Collection $collection, bool $value) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]unless의 반대 동작에 대해서는 when 메서드를 참고하세요.
unlessEmpty() {.collection-method}
whenNotEmpty 메서드의 별칭입니다.
unlessNotEmpty() {.collection-method}
whenEmpty 메서드의 별칭입니다.
unwrap() {.collection-method}
정적 unwrap 메서드는 주어진 값이 적용 가능한 경우, 해당 값의 기본이 되는 컬렉션 아이템을 반환합니다:
Collection::unwrap(collect('John Doe'));
// ['John Doe']
Collection::unwrap(['John Doe']);
// ['John Doe']
Collection::unwrap('John Doe');
// 'John Doe'value() {.collection-method}
value 메서드는 컬렉션의 첫 번째 요소에서 주어진 값을 조회합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Speaker', 'price' => 400],
]);
$value = $collection->value('price');
// 200values() {.collection-method}
values 메서드는 키를 연속된 정수로 재설정한 새로운 컬렉션을 반환합니다:
$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Speaker', 'price' => 400],
]);
$values = $collection->values();
$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Speaker', 'price' => 400],
]
*/when() {.collection-method}
when 메서드는 이 메서드에 전달된 첫 번째 인자가 true로 평가될 때 주어진 콜백을 실행합니다. 컬렉션 인스턴스와 when 메서드에 전달된 첫 번째 인자가 클로저에 전달됩니다:
$collection = collect([1, 2, 3]);
$collection->when(true, function (Collection $collection, bool $value) {
return $collection->push(4);
});
$collection->when(false, function (Collection $collection, bool $value) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 4]when 메서드에는 두 번째 콜백을 전달할 수 있습니다. 이 두 번째 콜백은 when 메서드에 전달된 첫 번째 인수가 false로 평가될 때 실행됩니다:
$collection = collect([1, 2, 3]);
$collection->when(false, function (Collection $collection, bool $value) {
return $collection->push(4);
}, function (Collection $collection, bool $value) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]when과 반대되는 동작은 unless 메서드를 참고하십시오.
whenEmpty() {.collection-method}
whenEmpty 메서드는 컬렉션이 비어 있을 때 주어진 콜백을 실행합니다:
$collection = collect(['Michael', 'Tom']);
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Adam');
});
$collection->all();
// ['Michael', 'Tom']
$collection = collect();
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Adam');
});
$collection->all();
// ['Adam']whenEmpty 메서드에는 컬렉션이 비어 있지 않을 때 실행될 두 번째 클로저를 전달할 수 있습니다:
$collection = collect(['Michael', 'Tom']);
```php
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Adam');
}, function (Collection $collection) {
return $collection->push('Taylor');
});
$collection->all();
// ['Michael', 'Tom', 'Taylor']whenEmpty의 반대 동작은 whenNotEmpty 메서드를 참고하십시오.
whenNotEmpty() {.collection-method}
whenNotEmpty 메서드는 컬렉션이 비어 있지 않을 때 주어진 콜백을 실행합니다:
$collection = collect(['Michael', 'Tom']);
$collection->whenNotEmpty(function (Collection $collection) {
return $collection->push('Adam');
});
$collection->all();
// ['Michael', 'Tom', 'Adam']
$collection = collect();
$collection->whenNotEmpty(function (Collection $collection) {
return $collection->push('Adam');
});
$collection->all();
// []whenNotEmpty 메서드에는 컬렉션이 비어 있을 때 실행할 두 번째 클로저를 전달할 수도 있습니다:
$collection = collect();
$collection->whenNotEmpty(function (Collection $collection) {
return $collection->push('Adam');
}, function (Collection $collection) {
return $collection->push('Taylor');
});
$collection->all();
// ['Taylor']whenNotEmpty의 반대 동작은 whenEmpty 메서드를 참고하십시오.
where() {.collection-method}
where 메서드는 주어진 키 / 값 쌍으로 컬렉션을 필터링합니다:
$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 메서드를 사용하고, null 값을 필터링하려면 whereNull 및 whereNotNull 메서드를 사용하세요.
선택적으로, 두 번째 매개변수로 비교 연산자를 전달할 수 있습니다. 지원되는 연산자는 다음과 같습니다: '===', '!==', '!=', '==', '=', '<>', '>', '<', '>=', '<=':
$collection = collect([
['name' => 'Jim', 'platform' => 'Mac'],
['name' => 'Sally', 'platform' => 'Mac'],
['name' => 'Sue', 'platform' => 'Linux'],
]);
$filtered = $collection->where('platform', '!=', 'Linux');
$filtered->all();
/*
[
['name' => 'Jim', 'platform' => 'Mac'],
['name' => 'Sally', 'platform' => 'Mac'],
]
*/whereStrict() {.collection-method}
이 메서드는 where 메서드와 시그니처가 동일하지만, 모든 값은 "엄격한" 비교를 사용하여 비교됩니다.
whereBetween() {.collection-method}
whereBetween 메서드는 지정된 아이템 값이 주어진 범위 내에 있는지 판별하여 컬렉션을 필터링합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]
*/whereIn() {.collection-method}
whereIn 메서드는 지정된 아이템 값이 주어진 배열에 포함되어 있지 않은 요소를 컬렉션에서 제거합니다:
$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' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
]
*/whereIn 메서드는 아이템 값을 확인할 때 "느슨한" 비교를 사용하므로, 정수 값을 가진 문자열은 동일한 값을 가진 정수와 같은 것으로 간주됩니다. "엄격한" 비교를 사용하여 필터링하려면 whereInStrict 메서드를 사용하세요.
whereInStrict() {.collection-method}
이 메서드는 whereIn 메서드와 동일한 시그니처를 가지고 있지만, 모든 값은 "엄격한" 비교를 사용하여 비교됩니다.
whereInstanceOf() {.collection-method}
whereInstanceOf 메서드는 주어진 클래스 타입으로 컬렉션을 필터링합니다:
use App\Models\User;
use App\Models\Post;
$collection = collect([
new User,
new User,
new Post,
]);
$filtered = $collection->whereInstanceOf(User::class);
$filtered->all();
// [App\Models\User, App\Models\User]whereNotBetween() {.collection-method}
whereNotBetween 메서드는 지정된 아이템 값이 주어진 범위를 벗어나는지 확인하여 컬렉션을 필터링합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 80],
```php
['product' => 'Pencil', 'price' => 30],
]
*/whereNotIn() {.collection-method}
whereNotIn 메서드는 주어진 배열에 포함된 특정 항목 값을 가진 요소를 컬렉션에서 제거합니다:
$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 메서드는 항목 값을 확인할 때 "느슨한(loose)" 비교를 사용합니다. 즉, 정수 값을 가진 문자열은 동일한 값을 가진 정수와 동일한 것으로 간주됩니다. "엄격한(strict)" 비교를 사용하여 필터링하려면 whereNotInStrict 메서드를 사용하세요.
whereNotInStrict() {.collection-method}
이 메서드는 whereNotIn 메서드와 시그니처가 동일하지만, 모든 값이 "엄격한(strict)" 비교를 사용하여 비교됩니다.
whereNotNull() {.collection-method}
whereNotNull 메서드는 주어진 키가 null이 아닌 컬렉션의 항목을 반환합니다:
$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
['name' => 0], ['name' => ''],
]);
$filtered = $collection->whereNotNull('name');
$filtered->all();
/*
[
['name' => 'Desk'],
['name' => 'Bookcase'],
['name' => 0],
['name' => ''],
]
*/whereNull() {.collection-method}
whereNull 메서드는 주어진 키의 값이 null인 컬렉션의 항목을 반환합니다:
$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
['name' => 0],
['name' => ''],
]);
$filtered = $collection->whereNull('name');
$filtered->all();
/*
[
['name' => null],
]
*/wrap() {.collection-method}
정적 메서드 wrap은 해당되는 경우 주어진 값을 컬렉션으로 감쌉니다:
use Illuminate\Support\Collection;
$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 = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]컬렉션
하이 오더 메시지 (Higher Order Messages)
컬렉션은 "하이 오더 메시지(Higher Order Messages)"라는 기능도 지원합니다. 이는 컬렉션에 자주 수행하는 작업을 훨씬 짧게 표현할 수 있게 해주는 일종의 문법적 단축키입니다. 하이 오더 메시지를 지원하는 컬렉션 메서드는 다음과 같습니다: average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, skipUntil, skipWhile, some, sortBy, sortByDesc, sum, takeUntil, takeWhile, unique.
각 하이 오더 메시지는 컬렉션 인스턴스의 동적 프로퍼티(dynamic property)처럼 접근할 수 있습니다. 예를 들어, each 하이 오더 메시지를 사용하면 컬렉션에 담긴 각 객체에 대해 특정 메서드를 간단히 호출할 수 있습니다:
use App\Models\User;
$users = User::where('votes', '>', 500)->get();
$users->each->markAsVip();위 코드는 아래처럼 클로저를 사용해 반복문을 직접 작성한 것과 동일하게 동작합니다. 다만 훨씬 간결합니다.
$users->each(function ($user) {
$user->markAsVip();
});마찬가지로 sum 하이 오더 메시지를 사용하면, 사용자 컬렉션에 담긴 모든 사용자의 "votes" 총합을 손쉽게 구할 수 있습니다:
$users = User::where('group', 'Development')->get();
return $users->sum->votes;NOTE
하이 오더 메시지는 "컬렉션에 들어 있는 각 요소에 대해 어떤 프로퍼티나 메서드를 일괄 적용한다"는 의미를 담고 있습니다. $users->each->markAsVip()처럼 작성하면 "컬렉션의 각 사용자에 대해 markAsVip()를 호출하라"는 의도를 코드만 보고도 직관적으로 파악할 수 있어, 실무에서 반복문 대신 즐겨 사용됩니다.
컬렉션
지연 컬렉션 (Lazy Collections)
소개
WARNING
지연 컬렉션(Lazy Collection)을 본격적으로 살펴보기 전에 PHP 제너레이터에 대해 먼저 알아두는 것이 좋습니다.
이미 강력한 기능을 제공하는 Collection 클래스를 보완하기 위해, LazyCollection 클래스는 PHP의 제너레이터를 활용하여 매우 큰 데이터셋을 다루면서도 메모리 사용량을 낮게 유지할 수 있게 해줍니다.
예를 들어, 애플리케이션에서 수 기가바이트에 달하는 로그 파일을 처리하면서 Laravel 컬렉션 메서드의 편리함도 그대로 활용하고 싶은 상황을 생각해봅시다. 파일 전체를 한 번에 메모리로 읽어들이는 대신, 지연 컬렉션을 사용하면 한 시점에 파일의 아주 작은 일부분만 메모리에 유지할 수 있습니다:
use App\Models\LogEntry;
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
$handle = fopen('log.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
fclose($handle);
})->chunk(4)->map(function (array $lines) {
return LogEntry::fromLines($lines);
})->each(function (LogEntry $logEntry) {
// 로그 항목 처리...
});또 다른 예로, 만 개의 Eloquent 모델을 순회해야 하는 상황을 생각해봅시다. 일반적인 Laravel 컬렉션을 사용하면 만 개의 Eloquent 모델을 한꺼번에 메모리에 로드해야 합니다:
use App\Models\User;
$users = User::all()->filter(function (User $user) {
return $user->id > 500;
});하지만 쿼리 빌더의 cursor 메서드는 LazyCollection 인스턴스를 반환합니다. 이 방식을 사용하면 데이터베이스에 대해 단 하나의 쿼리만 실행하면서도, 한 번에 하나의 Eloquent 모델만 메모리에 유지할 수 있습니다. 아래 예시에서 filter 콜백은 실제로 각 사용자를 하나씩 순회하기 전까지는 실행되지 않으므로, 메모리 사용량을 크게 줄일 수 있습니다:
use App\Models\User;
$users = User::cursor()->filter(function (User $user) {
return $user->id > 500;
});
foreach ($users as $user) {
echo $user->id;
}NOTE
일반 Collection은 배열처럼 모든 데이터를 미리 메모리에 담아두는 방식이라면, LazyCollection은 "필요한 순간에 필요한 만큼만" 값을 꺼내오는 파이프라인에 가깝습니다. 대용량 CSV 처리, 로그 분석, 대량의 DB 레코드 순회 등에서 특히 유용합니다.
지연 컬렉션 생성하기
지연 컬렉션 인스턴스를 생성하려면, 컬렉션의 make 메서드에 PHP 제너레이터 함수를 전달하면 됩니다:
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
$handle = fopen('log.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
fclose($handle);
});Enumerable 계약(Contract)
Collection 클래스에서 사용 가능한 메서드는 거의 대부분 LazyCollection 클래스에서도 동일하게 사용할 수 있습니다. 두 클래스 모두 Illuminate\Support\Enumerable 계약을 구현하며, 이 계약에는 다음과 같은 메서드들이 정의되어 있습니다:
all average avg chunk chunkBy chunkWhile collapse collect combine concat contains containsStrict count countBy crossJoin dd diff diffAssoc diffKeys dump duplicates duplicatesStrict each eachSpread every except filter first firstOrFail firstWhere flatMap flatten flip forPage get groupBy has implode intersect intersectAssoc intersectByKeys isEmpty isNotEmpty join keyBy keys last macro make map mapInto mapSpread mapToGroups mapWithKeys max median merge mergeRecursive min mode nth only pad partition pipe pluck random reduce reduceInto reject replace replaceRecursive reverse search shuffle skip slice sole some sort sortBy sortByDesc sortKeys sortKeysDesc split sum take tap times toArray toJson union unique uniqueStrict unless unlessEmpty unlessNotEmpty unwrap values when whenEmpty whenNotEmpty where whereStrict whereBetween whereIn whereInStrict whereInstanceOf whereNotBetween whereNotIn whereNotInStrict wrap zip
WARNING
shift, pop, prepend처럼 컬렉션 자체를 변경(mutate)하는 메서드는 LazyCollection 클래스에서는 사용할 수 없습니다.
지연 컬렉션 전용 메서드
Enumerable 계약에 정의된 메서드 외에도, LazyCollection 클래스는 다음과 같은 메서드를 추가로 제공합니다:
takeUntilTimeout() {.collection-method}
takeUntilTimeout 메서드는 지정된 시각까지만 값을 열거(enumerate)하는 새로운 지연 컬렉션을 반환합니다. 지정된 시각이 지나면 컬렉션은 열거를 중단합니다:
$lazyCollection = LazyCollection::times(INF)
->takeUntilTimeout(now()->plus(minutes: 1));
$lazyCollection->each(function (int $number) {
dump($number);
sleep(1);
});
// 1
// 2
// ...
// 58
// 59이 메서드의 활용 예시로, 커서를 이용해 데이터베이스에서 청구서(invoice)를 제출하는 애플리케이션을 생각해봅시다. 15분마다 실행되면서 최대 14분 동안만 청구서를 처리하도록 스케줄 작업을 정의할 수 있습니다:
use App\Models\Invoice;
use Illuminate\Support\Carbon;
Invoice::pending()->cursor()
->takeUntilTimeout(
Carbon::createFromTimestamp(LARAVEL_START)->add(14, 'minutes')
)
->each(fn (Invoice $invoice) => $invoice->submit());tapEach() {.collection-method}
each 메서드는 컬렉션의 모든 항목에 대해 즉시 콜백을 호출하는 반면, tapEach 메서드는 항목이 리스트에서 하나씩 실제로 꺼내질 때만 콜백을 호출합니다:
// 아직 아무것도 출력되지 않음...
$lazyCollection = LazyCollection::times(INF)->tapEach(function (int $value) {
dump($value);
});
// 세 개의 항목이 출력됨...
$array = $lazyCollection->take(3)->all();
// 1
// 2
// 3throttle() {.collection-method}
throttle 메서드는 지정한 초(second) 간격으로 값을 하나씩 반환하도록 지연 컬렉션의 속도를 제한합니다. 요청 속도 제한(rate limit)이 걸려있는 외부 API와 연동할 때 특히 유용합니다:
use App\Models\User;
User::where('vip', true)
->cursor()
->throttle(seconds: 1)
->each(function (User $user) {
// 외부 API 호출...
});remember() {.collection-method}
remember 메서드는 이미 열거된 값들을 기억해두었다가, 이후 컬렉션을 다시 열거할 때 해당 값들을 다시 조회하지 않는 새로운 지연 컬렉션을 반환합니다:
// 아직 쿼리가 실행되지 않음...
$users = User::cursor()->remember();
// 쿼리가 실행됨...
// 처음 5명의 사용자가 데이터베이스에서 조회되어 하이드레이션됨...
$users->take(5)->all();
// 처음 5명은 컬렉션의 캐시에서 가져옴...
// 나머지는 데이터베이스에서 조회되어 하이드레이션됨...
$users->take(20)->all();withHeartbeat() {.collection-method}
withHeartbeat 메서드를 사용하면 지연 컬렉션을 열거하는 동안 일정한 시간 간격마다 콜백을 실행할 수 있습니다. 락(lock)을 연장하거나 진행 상황을 업데이트하는 등, 주기적인 유지보수 작업이 필요한 장시간 실행 작업에서 특히 유용합니다:
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\Cache;
$lock = Cache::lock('generate-reports', seconds: 60 * 5);
if ($lock->get()) {
try {
Report::where('status', 'pending')
->lazy()
->withHeartbeat(
CarbonInterval::minutes(4),
fn () => $lock->extend(CarbonInterval::minutes(5))
)
->each(fn ($report) => $report->process());
} finally {
$lock->release();
}
}