컬렉션
번역일: 2026년 6월 20일
컬렉션
소개
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 클래스는 메서드를 체이닝하여 배열을 유창하게(fluently) 변환하고 가공할 수 있게 해줍니다. 컬렉션은 기본적으로 불변(immutable)입니다. 즉, 대부분의 Collection 메서드는 원본을 수정하지 않고 새로운 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');사용 가능한 메서드
이후 문서에서는 Collection 클래스에서 사용 가능한 각 메서드를 설명합니다. 이 메서드들은 모두 체이닝하여 배열을 유창하게 조작할 수 있으며, 거의 모든 메서드가 새로운 Collection 인스턴스를 반환하므로 필요할 때 원본 컬렉션을 보존할 수 있습니다.
after all average avg before chunk chunkWhile collapse collapseWithKeys collect combine concat contains containsOneItem containsStrict count countBy crossJoin dd diff diffAssoc diffAssocUsing diffKeys doesntContain dot dump duplicates duplicatesStrict each eachSpread ensure every except filter first firstOrFail firstWhere flatMap flatten flip forget forPage get groupBy has hasAny 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 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 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 메서드는 주어진 키의 평균값을 반환합니다.
$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">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach`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 인스턴스를 지연 방식이 아닌 일반 컬렉션으로 가져와야 할 때 유용합니다. collect()는 Enumerable 컨트랙트의 일부이므로 안전하게 Collection 인스턴스를 얻는 데 사용할 수 있습니다.
`combine()` {.collection-method}
combine 메서드는 컬렉션의 값을 키로, 다른 배열이나 컬렉션의 값을 값으로 결합합니다.
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]`concat()` {.collection-method}
concat 메서드는 주어진 array 또는 컬렉션의 값을 다른 컬렉션의 끝에 추가합니다.
$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 메서드는 컬렉션에 주어진 항목이 포함되어 있는지 확인합니다. 클로저를 전달하면 조건을 통과하는 요소가 있는지 확인할 수 있습니다.
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function (int $value, int $key) {
return $value > 5;
});
// false문자열을 전달하면 해당 값이 컬렉션에 있는지 확인합니다.
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false키/값 쌍을 전달하면 해당 쌍이 컬렉션에 존재하는지 확인합니다.
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// falsecontains 메서드는 값 비교 시 "느슨한" 비교를 사용합니다. "엄격한" 비교를 사용하려면 containsStrict 메서드를 사용하세요.
contains의 반대는 doesntContain 메서드입니다.
`containsOneItem()` {.collection-method}
containsOneItem 메서드는 컬렉션에 항목이 정확히 하나만 있는지 확인합니다.
collect([])->containsOneItem();
// false
collect(['1'])->containsOneItem();
// true
collect(['1', '2'])->containsOneItem();
// false`containsStrict()` {.collection-method}
contains 메서드와 시그니처가 같지만, 모든 값을 "엄격한" 비교로 처리합니다.
NOTE
Eloquent 컬렉션을 사용할 때는 이 메서드의 동작이 수정됩니다.
`count()` {.collection-method}
count 메서드는 컬렉션의 전체 항목 수를 반환합니다.
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4`countBy()` {.collection-method}
countBy 메서드는 컬렉션에서 값의 발생 횟수를 셉니다. 기본적으로 모든 요소의 발생 횟수를 계산합니다.
$collection = collect([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]클로저를 전달하면 사용자 정의 기준으로 항목을 집계할 수 있습니다.
$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);
$counted = $collection->countBy(function (string $email) {
return substr(strrchr($email, "@"), 1);
});
$counted->all();
// ['gmail.com' => 2, 'yahoo.com' => 1]`crossJoin()` {.collection-method}
crossJoin 메서드는 컬렉션의 값을 주어진 배열이나 컬렉션과 교차 결합하여 가능한 모든 순열의 카르테시안 곱을 반환합니다.
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/`dd()` {.collection-method}
dd 메서드는 컬렉션의 항목을 덤프하고 스크립트 실행을 종료합니다.
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: 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 메서드는 키와 값을 모두 기준으로 비교하여, 원본 컬렉션에는 있지만 주어진 컬렉션에는 없는 키/값 쌍을 반환합니다.
$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}
diffAssocUsing은 diffAssoc와 달리, 인덱스 비교에 사용자 정의 콜백 함수를 사용합니다.
$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보다 작거나, 같거나, 크거나 한 정수를 반환하는 비교 함수여야 합니다. 자세한 내용은 PHP의 array_diff_uassoc 문서를 참고하세요.
`diffKeys()` {.collection-method}
diffKeys 메서드는 키를 기준