Download the PHP package spatie/laravel-collection-macros without Composer
On this page you can find all versions of the php package spatie/laravel-collection-macros. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download spatie/laravel-collection-macros
More information about spatie/laravel-collection-macros
Files in spatie/laravel-collection-macros
Package laravel-collection-macros
Short Description A set of useful Laravel collection macros
License MIT
Homepage https://github.com/spatie/laravel-collection-macros
Informations about the package 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.
Support us
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.
Installation
You can pull in the package via composer:
The package will automatically register itself.
Macros
after
at
second
third
fourth
fifth
sixth
seventh
eighth
ninth
tenth
getNth
before
catch
chunkBy
collectBy
containsAny
containsAll
eachCons
extract
filterMap
firstOrFail
firstOrPush
fromPairs
getCaseInsensitive
glob
groupByModel
hasCaseInsensitive
head
if
ifAny
ifEmpty
insertAfter
insertAfterKey
insertAt
insertBefore
insertBeforeKey
none
paginate
path
pluckMany
pluckManyValues
pluckToArray
prioritize
recursive
rotate
sectionBy
simplePaginate
sliceBefore
tail
try
toPairs
transpose
validate
weightedRandom
withSize
after
Get the next item from the collection.
You can also pass a second parameter to be used as a fallback.
at
Retrieve an item at an index.
second
Retrieve item at the second index.
third
Retrieve item at the third index.
fourth
Retrieve item at the fourth index.
fifth
Retrieve item at the fifth index.
sixth
Retrieve item at the sixth index.
seventh
Retrieve item at the seventh index.
eighth
Retrieve item at the eighth index.
ninth
Retrieve item at the ninth index.
tenth
Retrieve item at the tenth index.
getNth
Retrieve item at the nth item.
before
Get the previous item from the collection.
You can also pass a second parameter to be used as a fallback.
catch
See Try
chunkBy
Chunks 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.
collectBy
Get an item at a given key, and collect it.
You can also pass a second parameter to be used as a fallback.
containsAny
Will return true
if one or more of the given values exist in the collection.
containsAll
Will return true
if all given values exist in the collection.
eachCons
Get 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.
extract
Extract keys from a collection. This is very similar to only
, with two key differences:
extract
returns an array of values, not an associative array- If a value doesn't exist, it will fill the value with
null
instead of omitting it
extract
is useful when using PHP 7.1 short list()
syntax.
filterMap
Map a collection and remove falsy values in one go.
firstOrFail
Get the first item. Throws Spatie\CollectionMacros\Exceptions\CollectionItemNotFound
if the item was not found.
firstOrPush
Retrieve 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.
Occasionally, you'll want to specify the target collection to be pushed to. You may pass this as a third parameter.
fromPairs
Transform a collection into an associative array form collection item.
getCaseInsensitive
Get the value of a given key.
If the key is a string, we'll search for the key using a case-insensitive comparison.
glob
Returns a collection of a glob()
result.
groupByModel
Similar 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.
Full signature: groupByModel($callback, $preserveKeys, $modelKey, $itemsKey)
hasCaseInsensitive
Determine 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.
head
Retrieves first item from the collection.
if
The if
macro can help branch collection chains. This is the signature of this macro:
$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:
When a closure is passed to $if
, $then
or $else
, the entire collection will be passed as an argument to that closure.
ifAny
Executes the passed callable if the collection isn't empty. The entire collection will be returned.
ifEmpty
Executes the passed callable if the collection is empty. The entire collection will be returned.
insertAfter
Inserts an item after the first occurrence of a given item and returns the updated Collection instance. Optionally a key can be given.
insertAfterKey
Inserts an item after a given key and returns the updated Collection instance. Optionally a key for the new item can be given.
insertAt
Inserts an item at a given index and returns the updated Collection instance. Optionally a key can be given.
insertBefore
Inserts an item before the first occurrence of a given item and returns the updated Collection instance. Optionally a key can be given.
insertBeforeKey
Inserts an item before a given key and returns the updated Collection instance. Optionally a key for the new item can be given.
none
Checks whether a collection doesn't contain any occurrences of a given item, key-value pair, or passing truth test. The function accepts the same parameters as the contains
collection method.
paginate
Create a LengthAwarePaginator
instance for the items in the collection.
This paginates the contents of $posts
with 5 items per page. paginate
accepts quite some options, head over to the Laravel docs for an in-depth guide.
path
Returns an item from the collection with multidimensional data using "dot" notation.
Works the same way as native Collection's pull
method, but without removing an item from the collection.
pluckMany
Returns a collection with only the specified keys.
pluckManyValues
Returns a collection with only the specified keys' values.
pluckToArray
Returns array of values of a given key.
prioritize
Move elements to the start of the collection.
recursive
Convert an array and its children to collection using recursion.
In some cases you may not want to turn all the children into a collection. You can convert only to a certain depth by providing a number to the recursive method.
This can be useful when you know that at a certain depth it'll not be necessary or that it may break your code.
rotate
Rotate the items in the collection with given offset
sectionBy
Splits a collection into sections grouped by a given key. Similar to groupBy
but respects the order of the items in the collection and reuses existing keys.
Full signature: sectionBy($callback, $preserveKeys, $sectionKey, $itemsKey)
simplePaginate
Create a Paginator
instance for the items in the collection.
This paginates the contents of $posts
with 5 items per page. simplePaginate
accepts quite some options, head over to the Laravel docs for an in-depth guide.
For a in-depth guide on pagination, check out the Laravel docs.
sliceBefore
Slice the values out from a collection before the given callback is true. If the optional parameter $preserveKeys
as true
is passed, it will preserve the original keys.
tail
Extract the tail from a collection. So everything except the first element. It's a shorthand for slice(1)->values()
, but nevertheless very handy. If the optional parameter $preserveKeys
as true
is passed, it will preserve the keys and fallback to slice(1)
.
toPairs
Transform a collection into an array with pairs.
transpose
The goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.
try
If any of the methods between try
and catch
throw an exception, then the exception can be handled in catch
.
While the methods are named try
/catch
for familiarity with PHP, the collection itself behaves more like a database transaction. So when an exception is thrown, the original collection (before the try) is returned.
You may gain access to the collection within catch by adding a second parameter to your handler. You may also manipulate the collection within catch by returning a value.
validate
Returns true
if the given $callback
returns true for every item. If $callback
is a string or an array, regard it as a validation rule.
weightedRandom
Returns a random item by a weight. In this example, the item with a
has the most chance to get picked, and the item with c
the least.
Alternatively, you can pass a callable to get the weight.
withSize
Create a new collection with the specified amount of items.
Changelog
Please see CHANGELOG for more information what has changed recently.
Testing
Contributing
Please see CONTRIBUTING for details.
Security
If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.
Credits
- Freek Van der Herten
- Sebastian De Deyne
- All Contributors
About Spatie
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
License
The MIT License (MIT). Please see License File for more information.