A set of useful Laravel collection macros
A set of useful Laravel collection macros
This repository contains some useful collection macros.
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
You can pull in the package via composer:
composer require spatie/laravel-collection-macrosThe package will automatically register itself.
afterat
catchchunkBycollectBycontainsAnycontainsAlleachConsextractfilterMapfirstOrPushfromPairsgetCaseInsensitiveglobgroupByModelhasCaseInsensitiveheadififAnyifEmptyinsertAfterinsertAfterKeyinsertAtinsertBeforeinsertBeforeKeynonepaginatepathpluckManypluckManyValuespluckToArrayprioritizerecursiverotatesectionBysimplePaginatesliceBeforetailtrytoPairstransposevalidateweightedRandomwithSizeafterGet the next item from the collection.
$collection = collect([1,2,3]);
$currentItem = 2;
$currentItem = $collection->after($currentItem); // return 3;
$collection->after($currentItem); // return null;
$currentItem = $collection->after(function($item) {
return $item > 1;
}); // return 3;You can also pass a second parameter to be used as a fallback.
$collection = collect([1,2,3]);
$currentItem = 3;
$collection->after($currentItem, $collection->first()); // return 1;atRetrieve an item at an index.
$data = new Collection([1, 2, 3]);
$data->at(0); // 1
$data->at(1); // 2
$data->at(-1); // 3secondRetrieve item at the second index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->second(); // 2thirdRetrieve item at the third index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->third(); // 3fourthRetrieve item at the fourth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->fourth(); // 4fifthRetrieve item at the fifth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->fifth(); // 5sixthRetrieve item at the sixth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->sixth(); // 6seventhRetrieve item at the seventh index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->seventh(); // 7eighthRetrieve item at the eighth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->eighth(); // 8ninthRetrieve item at the ninth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->ninth(); // 9tenthRetrieve item at the tenth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->tenth(); // 10getNthRetrieve item at the nth item.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
$data->getNth(11); // 11beforeGet the previous item from the collection.
$collection = collect([1,2,3]);
$currentItem = 2;
$currentItem = $collection->before($currentItem); // return 1;
$collection->before($currentItem); // return null;
$currentItem = $collection->before(function($item) {
return $item > 2;
}); // return 2;You can also pass a second parameter to be used as a fallback.
$collection = collect([1,2,3]);
$currentItem = 1;
$collection->before($currentItem, $collection->last()); // return 3;catchSee Try
chunkByChunks the values from a collection into groups as long the given callback is true. If the optional parameter $preserveKeys as true is passed, it will preserve the original keys.
collect(['A', 'A', 'B', 'A'])->chunkBy(function($item) {
return $item == 'A';
}); // return Collection([['A', 'A'],['B'], ['A']])collectByGet an item at a given key, and collect it.
$collection = collect([
'foo' => [1, 2, 3],
'bar' => [4, 5, 6],
]);
$collection->collectBy('foo'); // Collection([1, 2, 3])You can also pass a second parameter to be used as a fallback.
$collection = collect([
'foo' => [1, 2, 3],
'bar' => [4, 5, 6],
]);
$collection->collectBy('baz', ['Nope']); // Collection(['Nope'])containsAnyWill return true if one or more of the given values exist in the collection.
$collection = collect(['a', 'b', 'c']);
$collection->containsAny(['b', 'c', 'd']); // returns true
$collection->containsAny(['c', 'd', 'e']); // returns true
$collection->containsAny(['d', 'e', 'f']); // returns false
$collection->containsAny([]); // returns falsecontainsAllWill return true if all given values exist in the collection.
$collection = collect(['a', 'b', 'c']);
$collection->containsAll(['b', 'c',]); // returns true
$collection->containsAll(['c', 'd']); // returns false
$collection->containsAll(['d', 'e']); // returns false
$collection->containsAll([]); // returns trueeachConsGet the following consecutive neighbours in a collection from a given chunk size. If the optional parameter $preserveKeys as true is passed, it will preserve the original keys.
collect([1, 2, 3, 4])->eachCons(2); // return collect([[1, 2], [2, 3], [3, 4]])extractExtract keys from a collection. This is very similar to only, with two key differences:
extract returns an array of values, not an associative arraynull instead of omitting itextract is useful when using PHP 7.1 short list() syntax.
[$name, $role] = collect($user)->extract('name', 'role.name');filterMapMap a collection and remove falsy values in one go.
$collection = collect([1, 2, 3, 4, 5, 6])->filterMap(function ($number) {
$quotient = $number / 3;
return is_integer($quotient) ? $quotient : null;
});
$collection->toArray(); // returns [1, 2]firstOrPushRetrieve the first item using the callable given as the first parameter. If no value exists, push the value of the second parameter into the collection. You can pass a callable as the second parameter.
This method is really useful when dealing with cached class properties, where you want to store a value retrieved from an API or computationally expensive function in a collection to be used multiple times.
$collection = collect([1, 2, 3])->firstOrPush(fn($item) => $item === 4, 4);
$collection->toArray(); // returns [1, 2, 3, 4]Occasionally, you'll want to specify the target collection to be pushed to. You may pass this as a third parameter.
$collection = collect([1, 2, 3]);
$collection->filter()->firstOrPush(fn($item) => $item === 4, 4, $collection);
$collection->toArray(); // returns [1, 2, 3, 4]fromPairsTransform a collection into an associative array form collection item.
$collection = collect([['a', 'b'], ['c', 'd'], ['e', 'f']])->fromPairs();
$collection->toArray(); // returns ['a' => 'b', 'c' => 'd', 'e' => 'f']getCaseInsensitiveGet the value of a given key.
If the key is a string, we'll search for the key using a case-insensitive comparison.
$collection = collect([
'foo' => 'bar',
]);
$collection->getCaseInsensitive('Foo'); // returns 'bar';globReturns a collection of a glob() result.
Collection::glob('config/*.php');groupByModelSimilar to groupBy, but groups the collection by an Eloquent model. Since the key is an object instead of an integer or string, the results are divided into separate arrays.
$posts->groupByModel('category');
// [
// [$categoryA, [/*...$posts*/]],
// [$categoryB, [/*...$posts*/]],
// ];Full signature: groupByModel($callback, $preserveKeys, $modelKey, $itemsKey)
hasCaseInsensitiveDetermine if the collection contains a key with a given name.
If $key is a string, we'll search for the key using a case-insensitive comparison.
$collection = collect([
'foo' => 'bar',
]);
$collection->hasCaseInsensitive('Foo'); // returns true;headRetrieves first item from the collection.
$collection = collect([1,2,3]);
$collection->head(); // return 1
$collection = collect([]);
$collection->head(); // return nullifThe if macro can help branch collection chains. This is the signature of this macro:
if(mixed $if, mixed $then = null, mixed $else = null): mixed$if, $then and $else can be any type. If a closure is passed to any of these parameters, then that closure will be executed and the macro will use its results.
When $if returns a truthy value, then $then will be returned, otherwise $else will be returned.
Here are some examples:
collect()->if(true, then: true, else: false); // returns true
collect()->if(false, then: true, else: false); // returns falseWhen a closure is passed to $if, $then or $else, the entire collection will be passed as an argument to that closure.
…ifAnyExecutes the passed callable if the collection isn't empty. The entire collection will be returned.
collect()->ifAny(function(Collection $collection) { // empty collection so this won't get called
echo 'Hello';
});
collect([1, 2, 3])->ifAny(function(Collection $collection) { // non-empty collection so this will get called
echo 'Hello';
});ifEmptyExecutes the passed callable if the collection is empty. The entire collection will be returned.
collect()->ifEmpty(function(Collection $collection) { // empty collection so this will called
echo 'Hello';
});
collect([1, 2, 3])->ifEmpty(function(Collection $collection) { // non-empty collection so this won't get called
echo 'Hello';
});insertAfterInserts an item after the first occurrence of a given item and returns the updated Collection instance. Optionally a key can be given.
collect(['zero', 'two', 'three'])->insertAfter('zero', 'one');
// Collection contains ['zero', 'one', 'two', 'three']
collect(['zero' => 0, 'two' => 2, 'three' => 3]->insertAfter(0, 5, 'five');
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]insertAfterKeyInserts an item after a given key and returns the updated Collection instance. Optionally a key for the new item can be giv
No open issues yet, or sync has not completed.