컬렉션
번역일: 2026년 6월 21일
컬렉션
소개
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 클래스는 메서드를 체이닝하여 배열을 유연하게 변환하고 축약할 수 있습니다. 일반적으로 컬렉션은 불변(immutable)으로, 각 Collection 메서드는 완전히 새로운 Collection 인스턴스를 반환합니다.
컬렉션 생성
위에서 언급했듯이 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 클래스에서 사용 가능한 각 메서드를 설명합니다. 이 메서드들은 모두 체이닝하여 배열을 유연하게 조작할 수 있으며, 거의 모든 메서드가 새로운 Collection 인스턴스를 반환하므로 필요할 때 원본 컬렉션을 보존할 수 있습니다:
after all average avg before chunk 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 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 메서드는 주어진 키의 평균값을 반환합니다:
$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 메서드는 배열이나 컬렉션의 컬렉션을 단일 평면 컬렉션으로 합칩니다:
$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 컨트랙트의 일부이므로 안전하게 사용할 수 있습니다.
`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 메서드는 컬렉션에 주어진 항목이 포함되어 있는지 확인합니다. 클로저를 전달하면 주어진 조건을 통과하는 항목이 존재하는지 확인할 수 있습니다:
$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 메서드입니다.
`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 메서드는 컬렉션의 값을 주어진 배열이나 컬렉션과 교차 조인하여, 가능한 모든 순열의 카테시안 곱(Cartesian product)을 반환합니다:
$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();
/*
array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
*/스크립트 실행을 종료하지 않으려면 dump 메서드를 사용하세요.
`diff()` {.collection-method}
diff 메서드는 다른 컬렉션이나 PHP 배열과 값을 기준으로 비교하여, 원본 컬렉션에만 존재하는 값을 반환합니다:
$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 배열과 키/값 쌍을 기준으로 비교하여, 원본 컬렉션에만 존재하는 키/값 쌍을 반환합니다:
$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보다 작거나, 같거나, 큰 정수를 반환하는 비교 함수여야 합니다. 내부적으로 PHP의 array_diff_uassoc 함수를 사용합니다.
`diffKeys()` {.collection-method}
diffKeys 메서드는 다른 컬렉션이나 PHP 배열과 키를 기준으로 비교하여, 원본 컬렉션에만 존재하는 키/값 쌍을 반환합니다:
$collection =