컬렉션
업데이트됨번역일: 2026년 10월 3일
이 페이지는 원문이 업데이트되어 번역이 갱신되었습니다.
- 원문 수정
- 2026년 10월 3일
- 번역 갱신
- 2026년 10월 3일
컬렉션
소개
Illuminate\Support\Collection 클래스는 배열 데이터를 메서드 체이닝으로 편리하게 다룰 수 있도록 감싸 줍니다. 다음 예제는 collect 헬퍼로 배열에서 컬렉션 인스턴스를 만든 뒤, 각 요소에 strtoupper 함수를 적용하고 비어 있는 요소를 제거합니다:
$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) {
return strtoupper($name);
})->reject(function (string $name) {
return empty($name);
});이처럼 Collection의 메서드를 연결하면 원본 배열의 요소를 변환하거나 원하는 값으로 축약하는 작업을 순서대로 표현할 수 있습니다. 컬렉션 메서드는 일반적으로 새 Collection 인스턴스를 반환하므로 원본을 유지하면서 작업할 수 있습니다. 다만 원본을 직접 변경하는 메서드도 있으므로 각 메서드의 설명을 확인하세요.
컬렉션 만들기
앞서 살펴본 것처럼 collect 헬퍼는 전달한 배열을 담은 새 Illuminate\Support\Collection 인스턴스를 반환합니다. 다음과 같이 간단하게 컬렉션을 만들 수 있습니다:
$collection = collect([1, 2, 3]);make 또는 fromJson 메서드로도 컬렉션을 만들 수 있습니다.
NOTE
Eloquent에서 여러 모델을 조회한 결과는 Collection 인스턴스로 반환됩니다.
컬렉션 확장하기
컬렉션은 매크로를 지원하므로 실행 중에 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 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기본적으로 이 메서드는 느슨한 비교를 사용합니다. 따라서 정수를 담은 문자열과 같은 값의 정수를 동일하게 취급합니다. 타입까지 일치해야 하는 엄격한 비교를 사용하려면 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을 반환합니다. strict 인수로 엄격한 비교를 사용하거나 클로저로 검색 조건을 지정할 수도 있습니다:
$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`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 메서드는 배열이나 컬렉션으로 이루어진 컬렉션을 하나의 평탄한 컬렉션으로 합칩니다:
$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
Enumerable 인스턴스에서 지연 평가를 사용하지 않는 컬렉션이 필요할 때 collect 메서드가 특히 유용합니다. 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 메서드는 주어진 배열이나 컬렉션의 값들을 현재 컬렉션의 끝에 덧붙입니다:
$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 메서드는 컬렉션의 값과 주어진 배열 또는 컬렉션들을 교차 결합하여, 가능한 모든 조합인 데카르트 곱을 반환합니다:
$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 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}
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 메서드는 현재 컬렉션과 다른 컬렉션 또는 일반 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]`doesntContain()` {.collection-method}
doesntContain 메서드는 컬렉션에 특정 항목이 없는지 확인합니다. 클로저를 전달하면 주어진 조건을 만족하는 항목이 하나도 없는지 확인할 수 있습니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->doesntContain(function (int $value, int $key) {
return $value < 5;
});
// false문자열을 전달하면 해당 값이 컬렉션에 없는지 확인할 수 있습니다:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->doesntContain('Table');
// true
$collection->doesntContain('Desk');
// false키와 값을 함께 전달하면 해당 키 / 값 쌍을 가진 항목이 컬렉션에 없는지 확인할 수 있습니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->doesntContain('product', 'Bookcase');
// truedoesntContain 메서드는 값을 확인할 때 느슨한 비교를 사용하므로, 정수를 담은 문자열과 같은 값의 정수를 동일하게 취급합니다.
`doesntContainStrict()` {.collection-method}
doesntContain과 인수 구성은 같지만, 모든 값을 엄격하게 비교합니다.
`dot()` {.collection-method}
dot 메서드는 중첩된 컬렉션을 한 단계로 펼치고, 원래의 깊이를 점 표기법으로 나타냅니다:
$collection = collect(['products' => ['desk' => ['price' => 100]]]);
$flattened = $collection->dot();
$flattened->all();
// ['products.desk.price' => 100]`dump()` {.collection-method}
dump 메서드는 컬렉션의 항목을 덤프합니다:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
*/덤프한 뒤 스크립트 실행까지 종료하려면 dd 메서드를 사용하세요.
`duplicates()` {.collection-method}
duplicates 메서드는 컬렉션에서 중복된 값을 찾아 반환합니다:
$collection = collect(['a', 'b', 'a', 'c', 'b']);
$collection->duplicates();
// [2 => 'a', 4 => 'b']컬렉션에 배열이나 객체가 들어 있다면, 중복 여부를 확인할 속성의 키를 전달할 수 있습니다:
$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}
duplicates와 인수 구성은 같지만, 모든 값을 엄격하게 비교합니다.
`each()` {.collection-method}
each 메서드는 컬렉션의 항목을 순회하며 각 항목을 클로저에 전달합니다:
$collection = collect([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
// ...
});순회를 중단하려면 클로저에서 false를 반환합니다:
$collection->each(function (int $item, int $key) {
if (/* condition */) {
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인수 없이 호출하면 컬렉션의 첫 번째 요소를 가져옵니다. 컬렉션이 비어 있으면 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...인수 없이 호출하면 컬렉션의 첫 번째 요소를 가져옵니다. 컬렉션이 비어 있으면 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]비교 연산자를 지정할 수도 있습니다:
$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]where처럼 인수를 하나만 전달할 수도 있습니다. 이 경우 지정한 키의 값이 참으로 평가되는 첫 번째 항목을 반환합니다:
$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'];필요하면 펼칠 깊이를 인수로 전달할 수 있습니다:
$collection = collect([
'Apple' => [
[
'name' => 'iPhone 6S',
'brand' => 'Apple'
],
],
'Samsung' => [
[
'name' => 'Galaxy S7',
'brand' => 'Samsung'
],
],
]);
$products = $collection->flatten(1);
$products->values()->all();
/*
[
['name' => 'iPhone 6S', 'brand' => 'Apple'],
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/이 예제에서 깊이를 지정하지 않고 flatten을 호출하면 내부 배열까지 모두 펼쳐져 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']이 됩니다. 깊이를 지정하면 중첩 배열을 몇 단계까지 펼칠지 제어할 수 있습니다.
`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']);
// Forget a single key...
$collection->forget('name');
// ['framework' => 'Laravel']
// Forget multiple keys...
$collection->forget(['name', 'framework']);
// []WARNING
대부분의 컬렉션 메서드와 달리 forget은 수정된 새 컬렉션을 만들지 않습니다. 호출한 컬렉션 자체를 수정하고 반환합니다.
`forPage()` {.collection-method}
forPage 메서드는 지정한 페이지에 해당하는 항목들을 담은 새 컬렉션을 반환합니다. 첫 번째 인수는 페이지 번호, 두 번째 인수는 페이지당 항목 수입니다:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]`fromJson()` {.collection-method}
정적 메서드 fromJson은 PHP의 json_decode 함수로 주어진 JSON 문자열을 디코딩하여 새 컬렉션 인스턴스를 만듭니다:
use Illuminate\Support\Collection;
$json = json_encode([
'name' => 'Taylor Otwell',
'role' => 'Developer',
'status' => 'Active',
]);
$collection = Collection::fromJson($json);`get()` {.collection-method}
get 메서드는 지정한 키의 항목을 반환합니다. 키가 없으면 null을 반환합니다:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$value = $collection->get('name');
// Taylor두 번째 인수로 기본값을 지정할 수 있습니다:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$value = $collection->get('age', 34);
// 34기본값으로 콜백을 전달할 수도 있습니다. 지정한 키가 없으면 콜백을 실행한 결과를 반환합니다:
$collection->get('email', function () {
return 'taylor@example.com';
});
// 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'],
],
]
*/문자열 키 대신 콜백을 전달할 수도 있습니다. 콜백은 그룹의 키로 사용할 값을 반환해야 합니다:
$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([
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_3' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
],
'Role_2' => [
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
],
2 => [
'Role_1' => [
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
],
'Role_2' => [
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
],
],
];
*/`has()` {.collection-method}
has 메서드는 지정한 키가 컬렉션에 있는지 확인합니다. 키를 여러 개 전달하면 모든 키가 있어야 true를 반환합니다:
$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 메서드는 컬렉션의 항목을 하나의 문자열로 연결합니다. 인수는 항목의 타입에 따라 달라집니다. 배열이나 객체로 이루어진 컬렉션이라면 연결할 속성의 키와 값 사이에 넣을 구분 문자열을 전달합니다:
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// 'Desk, Chair'단순 문자열이나 숫자로 이루어진 컬렉션이라면 구분 문자열만 전달합니다:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'연결하기 전에 값의 형식을 바꾸려면 클로저를 전달할 수 있습니다:
$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']);
$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 메서드는 주어진 조건을 만족하는 마지막 요소를 반환합니다:
collect([1, 2, 3, 4])->last(function (int $value, int $key) {
return $value < 3;
});
// 2인수 없이 호출하면 컬렉션의 마지막 요소를 가져옵니다. 컬렉션이 비어 있으면 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']두 번째 인수로 시작 오프셋을 지정할 수 있습니다:
$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 배열 구조 분해와 함께 사용하면 두 컬렉션을 각각 변수에 담을 수 있습니다:
$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']점 표기법으로 중첩된 값도 가져올 수 있습니다:
$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']]결과 키가 중복되면 마지막으로 일치한 항목의 값이 남습니다:
$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]정수를 전달하면 컬렉션 끝에서 여러 항목을 제거해 컬렉션으로 반환합니다. 반환 순서는 끝에서 꺼내는 순서입니다:
$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 - (retrieved randomly)정수를 전달하면 가져올 항목 수를 지정할 수 있습니다. 개수를 명시하면 항목을 담은 컬렉션을 항상 반환합니다:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)요청한 개수가 컬렉션의 항목 수보다 많으면 InvalidArgumentException을 던집니다.
random 메서드는 클로저도 받습니다. 클로저에는 현재 컬렉션이 전달되며, 가져올 개수를 계산해 반환할 수 있습니다:
use Illuminate\Support\Collection;
$random = $collection->random(fn (Collection $items) => min(10, count($items)));
$random->all();
// [1, 2, 3, 4, 5] - (retrieved randomly)`range()` {.collection-method}
range 메서드는 지정한 범위의 양 끝값을 포함하는 정수 컬렉션을 반환합니다:
$collection = collect()->range(3, 6);
$collection->all();
// [3, 4, 5, 6]`reduce()` {.collection-method}
reduce 메서드는 매 순회의 결과를 다음 순회에 전달하면서 컬렉션을 하나의 값으로 누적합니다:
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function (?int $carry, int $item) {
return $carry + $item;
});
// 6첫 순회의 $carry는 기본적으로 null입니다. 두 번째 인수로 초기값을 지정할 수 있습니다:
$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 메서드는 전달한 초기값을 직접 수정하면서 컬렉션을 하나의 값으로 누적합니다. 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 메서드는 여러 누적값을 배열로 반환하고, 각 순회의 결과를 다음 순회로 전달합니다. 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) {
return $value > 2;
});
$filtered->all();
// [1, 2]reject와 반대로 조건을 만족하는 항목만 남기려면 filter 메서드를 참고하세요.
`replace()` {.collection-method}
replace 메서드는 merge와 비슷하지만, 문자열 키뿐 아니라 숫자 키가 일치하는 항목도 덮어씁니다:
$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',
2 => 'c',
1 => 'b',
0 => 'a',
]
*/`search()` {.collection-method}
search 메서드는 주어진 값을 찾아 해당 키를 반환합니다. 찾지 못하면 false를 반환합니다:
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1기본적으로 느슨한 비교를 사용하므로 정수를 담은 문자열과 같은 값의 정수를 동일하게 취급합니다. 타입까지 확인하는 엄격한 비교를 사용하려면 두 번째 인수를 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}
shift 메서드는 컬렉션의 첫 번째 항목을 제거하고 반환합니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]정수를 전달하면 컬렉션 앞에서 여러 항목을 제거해 컬렉션으로 반환합니다:
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift(3);
// collect([1, 2, 3])
$collection->all();
// [4, 5]`shuffle()` {.collection-method}
shuffle 메서드는 컬렉션 항목의 순서를 무작위로 섞습니다:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)`skip()` {.collection-method}
skip 메서드는 앞에서 지정한 개수의 요소를 건너뛴 새 컬렉션을 반환합니다:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$collection = $collection->skip(4);
$collection->all();
// [5, 6, 7, 8, 9, 10]`skipUntil()` {.collection-method}
skipUntil 메서드는 콜백이 false를 반환하는 동안 앞쪽 항목을 건너뜁니다. 처음 true를 반환한 항목부터 나머지 전체를 새 컬렉션으로 반환합니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->skipUntil(function (int $item) {
return $item >= 3;
});
$subset->all();
// [3, 4]값을 직접 전달하면 해당 값이 나올 때까지 앞쪽 항목을 건너뜁니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->skipUntil(3);
$subset->all();
// [3, 4]WARNING
지정한 값을 찾지 못하거나 콜백이 한 번도 true를 반환하지 않으면 빈 컬렉션을 반환합니다.
`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를 반환하지 않으면 빈 컬렉션을 반환합니다.
`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]반환된 컬렉션은 기본적으로 원래 키를 유지합니다. 키를 새로 매기려면 values 메서드를 사용하세요.
`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 ($previous, $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;
});
// 2키 / 값 쌍을 전달할 수도 있습니다. 해당 쌍과 일치하는 요소가 정확히 하나일 때만 반환합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->sole('product', 'Chair');
// ['product' => 'Chair', 'price' => 100]인수 없이 호출하면 컬렉션 전체에 요소가 정확히 하나 있을 때 해당 요소를 반환합니다:
$collection = collect([
['product' => 'Desk', 'price' => 200],
]);
$collection->sole();
// ['product' => 'Desk', 'price' => 200]sole이 반환할 요소가 없으면 \Illuminate\Support\ItemNotFoundException 예외를 던집니다. 반환할 요소가 둘 이상이면 \Illuminate\Support\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에 전달할 수 있습니다. 내부적으로 사용하는 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],
]
*/두 번째 인수로 정렬 플래그를 전달할 수 있습니다:
$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']],
]
*/여러 속성을 기준으로 정렬하려면 정렬 조건 배열을 전달합니다. 각 조건은 정렬할 속성과 정렬 방향으로 이루어진 배열이어야 합니다:
$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, 양수 중 하나의 정수를 반환해야 합니다. 자세한 내용은 내부적으로 사용하는 PHP 함수 uksort의 문서를 참고하세요.
`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']);
});
// 6`take()` {.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]값을 직접 전달하면 해당 값이 나오는 항목 직전까지 가져옵니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeUntil(3);
$subset->all();
// [1, 2]WARNING
지정한 값을 찾지 못하거나 콜백이 한 번도 true를 반환하지 않으면 모든 항목을 반환합니다.
`takeWhile()` {.collection-method}
takeWhile 메서드는 콜백이 true를 반환하는 동안 항목을 가져오며, 처음 false를 반환하는 항목 직전에서 멈춥니다:
$collection = collect([1, 2, 3, 4]);
$subset = $collection->takeWhile(function (int $item) {
return $item < 3;
});
$subset->all();
// [1, 2]WARNING
콜백이 한 번도 false를 반환하지 않으면 모든 항목을 반환합니다.
`tap()` {.collection-method}
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는 클로저를 지정한 횟수만큼 호출하고, 각 반환값으로 새 컬렉션을 만듭니다:
$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 메서드는 점 표기법을 사용하는 일차원 컬렉션을 중첩된 컬렉션으로 확장합니다:
$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" => [
"line_1" => "2992 Eagle Drive",
"line_2" => "",
"suburb" => "Detroit",
"state" => "MI",
"postcode" => "48219",
],
]
*/`union()` {.collection-method}
union 메서드는 주어진 배열을 컬렉션에 합칩니다. 키가 겹치면 원래 컬렉션의 값을 우선합니다:
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['d']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]`unique()` {.collection-method}
unique 메서드는 중복을 제거한 항목들을 반환합니다. 원래 배열 키를 유지하므로, 다음 예제에서는 values를 사용해 키를 연속된 숫자 인덱스로 다시 매깁니다:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]항목이 중첩 배열이나 객체라면 중복 판단에 사용할 키를 지정할 수 있습니다:
$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'],
]
*/클로저를 전달해 중복 판단에 사용할 값을 직접 계산할 수도 있습니다:
$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 메서드는 느슨한 비교로 값을 확인하므로, 정수를 담은 문자열과 같은 값의 정수를 동일하게 취급합니다. 엄격한 비교로 중복을 제거하려면 uniqueStrict를 사용하세요.
NOTE
Eloquent 컬렉션에서는 이 메서드의 동작이 달라집니다.
`uniqueStrict()` {.collection-method}
unique와 인수 구성은 같지만, 모든 값을 엄격하게 비교합니다.
`unless()` {.collection-method}
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]두 번째 콜백을 전달할 수도 있습니다. 이 콜백은 첫 번째 인수가 참으로 평가될 때 실행됩니다:
$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');
// 200`values()` {.collection-method}
values 메서드는 키를 0부터 시작하는 연속된 정수로 다시 매긴 새 컬렉션을 반환합니다:
$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 메서드는 첫 번째 인수가 참으로 평가될 때 콜백을 실행합니다. 클로저에는 컬렉션 인스턴스와 첫 번째 인수의 값이 전달됩니다:
$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]두 번째 콜백을 전달할 수도 있습니다. 이 콜백은 첫 번째 인수가 거짓으로 평가될 때 실행됩니다:
$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']두 번째 클로저를 전달하면 컬렉션이 비어 있지 않을 때 실행됩니다:
$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']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();
// []두 번째 클로저를 전달하면 컬렉션이 비어 있을 때 실행됩니다:
$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],
['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은 느슨한 비교를 사용하므로, 정수를 담은 문자열과 같은 값의 정수를 동일하게 취급합니다. 엄격한 비교가 필요하면 whereNotInStrict를 사용하세요.
`whereNotInStrict()` {.collection-method}
whereNotIn과 인수 구성은 같지만, 모든 값을 엄격하게 비교합니다.
`whereNotNull()` {.collection-method}
whereNotNull 메서드는 지정한 키의 값이 null이 아닌 항목을 반환합니다. 0과 빈 문자열은 그대로 남습니다:
$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)'를 지원합니다. 지원하는 메서드는 average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, skipUntil, skipWhile, some, sortBy, sortByDesc, sum, takeUntil, takeWhile, unique입니다.
고차 메시지는 컬렉션 인스턴스의 동적 속성으로 접근합니다. 예를 들어 each를 사용하면 컬렉션 안의 모든 객체에 같은 메서드를 호출할 수 있습니다:
use App\Models\User;
$users = User::where('votes', '>', 500)->get();
$users->each->markAsVip();마찬가지로 sum을 사용하면 사용자 컬렉션의 votes 값을 모두 더할 수 있습니다:
$users = User::where('group', 'Development')->get();
return $users->sum->votes;지연 컬렉션
소개
WARNING
Laravel의 지연 컬렉션을 학습하기 전에 PHP 제너레이터에 익숙해지는 것이 좋습니다.
LazyCollection은 Collection의 기능에 PHP 제너레이터를 결합하여, 메모리 사용량을 낮게 유지하면서 매우 큰 데이터셋을 처리할 수 있게 합니다.
예를 들어 수 GB 크기의 로그 파일을 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 (LazyCollection $lines) {
return LogEntry::fromLines($lines);
})->each(function (LogEntry $logEntry) {
// Process the log entry...
});Eloquent 모델 10,000개를 순회하는 경우도 생각해 볼 수 있습니다. 일반 Laravel 컬렉션을 사용하면 모델 10,000개를 동시에 메모리에 올려야 합니다:
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;
}지연 컬렉션 생성
지연 컬렉션을 만들려면 PHP 제너레이터 함수를 make 메서드에 전달합니다:
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
$handle = fopen('log.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
fclose($handle);
});Enumerable 계약
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처럼 컬렉션 자체를 변경하는 메서드는 LazyCollection에서 사용할 수 없습니다.
지연 컬렉션 메서드
LazyCollection은 Enumerable 계약의 메서드 외에도 다음 메서드를 제공합니다:
`takeUntilTimeout()` {.collection-method}
takeUntilTimeout 메서드는 지정한 시각까지 값을 순회하는 새 지연 컬렉션을 반환합니다. 해당 시각이 지나면 순회를 중단합니다:
$lazyCollection = LazyCollection::times(INF)
->takeUntilTimeout(now()->plus(minutes: 1));
$lazyCollection->each(function (int $number) {
dump($number);
sleep(1);
});
// 1
// 2
// ...
// 58
// 59예를 들어 커서로 데이터베이스의 청구서를 읽어 제출하는 애플리케이션에서, 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는 항목이 하나씩 실제로 꺼내질 때만 콜백을 실행합니다:
// Nothing has been dumped so far...
$lazyCollection = LazyCollection::times(INF)->tapEach(function (int $value) {
dump($value);
});
// Three items are dumped...
$array = $lazyCollection->take(3)->all();
// 1
// 2
// 3`throttle()` {.collection-method}
throttle 메서드는 지정한 초 간격으로 값을 반환하도록 지연 컬렉션의 처리 속도를 제한합니다. 요청 빈도를 제한하는 외부 API를 호출할 때 특히 유용합니다:
use App\Models\User;
User::where('vip', true)
->cursor()
->throttle(seconds: 1)
->each(function (User $user) {
// Call external API...
});`remember()` {.collection-method}
remember 메서드는 이미 순회한 값을 기억하는 새 지연 컬렉션을 반환합니다. 이후 다시 순회할 때는 해당 값을 다시 가져오지 않고 캐시된 값을 사용합니다:
// No query has been executed yet...
$users = User::cursor()->remember();
// The query is executed...
// The first 5 users are hydrated from the database...
$users->take(5)->all();
// First 5 users come from the collection's cache...
// The rest are hydrated from the database...
$users->take(20)->all();`withHeartbeat()` {.collection-method}
withHeartbeat 메서드는 지연 컬렉션을 순회하는 동안 일정한 시간 간격으로 콜백을 실행할 수 있게 합니다. 잠금의 유효 기간을 연장하거나 진행 상황을 알리는 등, 주기적인 유지 작업이 필요한 장시간 처리에 특히 유용합니다:
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->refresh()
)
->each(fn ($report) => $report->process());
} finally {
$lock->release();
}
}