Loading repository data…
Loading repository data…
spatie / repository
A set of useful Laravel collection macros
A transparent discovery signal based on current public GitHub metadata.
This score does not audit code, security, maintainers, documentation quality, or suitability. Verify the repository and its current documentation before adoption.
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-macros
The package will automatically register itself.
afterat
catchchunkBycollectBycontainsAnycontainsAlleachConsextractfilterMapfirstOrPushfromPairsgetCaseInsensitiveglobgroupByModelafterGet 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); // 3
secondRetrieve item at the second index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->second(); // 2
thirdRetrieve item at the third index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->third(); // 3
fourthRetrieve item at the fourth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->fourth(); // 4
fifthRetrieve item at the fifth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->fifth(); // 5
sixthRetrieve item at the sixth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->sixth(); // 6
seventhRetrieve item at the seventh index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->seventh(); // 7
eighthRetrieve item at the eighth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->eighth(); // 8
ninthRetrieve item at the ninth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->ninth(); // 9
tenthRetrieve item at the tenth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->tenth(); // 10
getNthRetrieve item at the nth item.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
$data->getNth(11); // 11
beforeGet 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 false
containsAllWill 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 true
eachConsGet 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 null
ifThe 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 false
When a closure is passed to $if, $then or $else, the entire collection will be passed as an argument to that closure.
// the `then` closure will be executed
// the first element of the returned collection now contains "THIS IS THE VALU
hasCaseInsensitive