Top Related Projects
The Laravel Framework.
A Collections-only split from Laravel's Illuminate Support
⚡️ Laravel components that take care of one specific task
Easily build Eloquent queries from API requests
Powerful data objects for Laravel
Quick Overview
Laravel Collection Macros is a package that extends Laravel's Collection class with additional useful methods. It provides a set of macros that can be used to manipulate and transform collections in various ways, enhancing the functionality of Laravel's already powerful collection system.
Pros
- Adds numerous useful methods to Laravel collections, increasing productivity
- Well-documented and easy to use
- Regularly maintained and updated
- Seamlessly integrates with existing Laravel projects
Cons
- May introduce unnecessary complexity for smaller projects
- Some macros might overlap with existing Laravel functionality
- Learning curve for developers unfamiliar with all the added methods
- Potential performance impact when using certain macros on large collections
Code Examples
- Using the
ifAny
macro to conditionally execute a callback:
$collection = collect([1, 2, 3, 4, 5]);
$result = $collection->ifAny(function ($item) {
return $item > 3;
}, function ($collection) {
return $collection->sum();
}, function ($collection) {
return $collection->average();
});
// Result: 15 (sum of the collection)
- Using the
groupByModel
macro to group items by a related model:
$collection = collect([
['id' => 1, 'user_id' => 1, 'name' => 'Item 1'],
['id' => 2, 'user_id' => 2, 'name' => 'Item 2'],
['id' => 3, 'user_id' => 1, 'name' => 'Item 3'],
]);
$result = $collection->groupByModel('user_id', User::class);
// Result: Collection of User models with associated items
- Using the
transpose
macro to transpose a collection of arrays:
$collection = collect([
['A', 'B', 'C'],
[1, 2, 3],
['a', 'b', 'c'],
]);
$result = $collection->transpose();
// Result: [['A', 1, 'a'], ['B', 2, 'b'], ['C', 3, 'c']]
Getting Started
To use Laravel Collection Macros in your project, follow these steps:
-
Install the package via Composer:
composer require spatie/laravel-collection-macros
-
The package will automatically register itself in Laravel 5.5+. For older versions, add the service provider to
config/app.php
:'providers' => [ // ... Spatie\CollectionMacros\CollectionMacroServiceProvider::class, ],
-
Start using the new macros in your Laravel collections:
$result = collect([1, 2, 3, 4, 5])->ifAny(function ($item) { return $item > 3; }, function ($collection) { return $collection->sum(); });
Competitor Comparisons
The Laravel Framework.
Pros of Laravel Framework
- Comprehensive full-stack framework with built-in features for routing, authentication, and more
- Extensive documentation and large community support
- Regular updates and long-term support
Cons of Laravel Framework
- Larger footprint and potentially slower performance due to its full-stack nature
- Steeper learning curve for beginners compared to focused packages
- May include unnecessary features for projects that only need collection enhancements
Code Comparison
Laravel Framework:
$collection = collect([1, 2, 3, 4, 5]);
$filtered = $collection->filter(function ($value) {
return $value > 2;
});
Laravel Collection Macros:
$collection = collect([1, 2, 3, 4, 5]);
$filtered = $collection->filterFast(fn($value) => $value > 2);
Summary
Laravel Framework offers a complete ecosystem for web application development, while Laravel Collection Macros focuses specifically on enhancing Laravel's collection functionality. The framework provides a more comprehensive solution but may be overkill for projects that only need collection improvements. Laravel Collection Macros offers a lightweight alternative for developers seeking to extend collection capabilities without the full framework overhead.
A Collections-only split from Laravel's Illuminate Support
Pros of collect
- Standalone package, usable outside of Laravel
- Lighter weight, focused solely on collection functionality
- More frequent updates and releases
Cons of collect
- Fewer macros and helper methods compared to laravel-collection-macros
- May lack some Laravel-specific integrations
- Potentially less comprehensive documentation
Code Comparison
laravel-collection-macros:
collect([1, 2, 3, 4])->ifAny(fn($item) => $item > 2, function ($collection) {
return $collection->sum();
});
collect:
collect([1, 2, 3, 4])->when(fn($collection) => $collection->contains(fn($item) => $item > 2), function ($collection) {
return $collection->sum();
});
Summary
laravel-collection-macros is a Laravel-specific package that extends the Collection class with numerous additional macros and helper methods. It's deeply integrated with Laravel and offers a wide range of functionality.
collect, on the other hand, is a standalone package that provides core collection functionality without Laravel dependencies. It's more lightweight and can be used in non-Laravel projects, but may lack some of the extensive features found in laravel-collection-macros.
Choose laravel-collection-macros for Laravel projects requiring extensive collection manipulation, or collect for lighter, framework-agnostic collection handling.
⚡️ Laravel components that take care of one specific task
Pros of Laravel Actions
- Provides a structured way to encapsulate business logic into reusable classes
- Allows actions to be used as controllers, jobs, or event listeners
- Offers a clean separation of concerns and improves code organization
Cons of Laravel Actions
- Requires learning a new concept and pattern specific to this package
- May introduce additional complexity for simpler applications
- Potential overhead in creating separate action classes for small operations
Code Comparison
Laravel Actions:
class CreateUser extends Action
{
public function handle(string $name, string $email)
{
return User::create(compact('name', 'email'));
}
}
Laravel Collection Macros:
collect($users)->transpose()->map(function ($item) {
return $item->implode(', ');
});
Summary
Laravel Actions focuses on organizing business logic into reusable classes, while Laravel Collection Macros extends Laravel's collection functionality with additional methods. Laravel Actions offers better code structure and versatility in how actions can be used, but it introduces a new concept to learn. Laravel Collection Macros is simpler to integrate and use within existing Laravel projects, but it's limited to enhancing collection operations.
Easily build Eloquent queries from API requests
Pros of laravel-query-builder
- Simplifies complex query building for API requests
- Provides a more declarative approach to filtering, sorting, and including relations
- Enhances API performance by reducing unnecessary data fetching
Cons of laravel-query-builder
- Steeper learning curve for developers new to the package
- May introduce additional complexity for simple queries
- Requires careful configuration to prevent potential security vulnerabilities
Code Comparison
laravel-query-builder:
$users = QueryBuilder::for(User::class)
->allowedFilters(['name', 'email'])
->allowedSorts(['name', 'created_at'])
->allowedIncludes(['posts'])
->paginate();
laravel-collection-macros:
$users = User::all()->filter(function ($user) {
return $user->name === 'John' || $user->email === 'john@example.com';
})->sortBy('name')->paginate();
The laravel-query-builder example demonstrates a more concise and declarative approach to building complex queries, while laravel-collection-macros relies on collection methods and closures for similar functionality. laravel-query-builder is better suited for API-driven applications, whereas laravel-collection-macros provides additional utility methods for working with collections in various scenarios.
Powerful data objects for Laravel
Pros of laravel-data
- Provides a structured way to handle data objects, improving type safety and data consistency
- Offers built-in validation and casting capabilities
- Supports automatic API resource generation and OpenAPI schema creation
Cons of laravel-data
- Requires more setup and boilerplate code compared to collection macros
- May introduce a steeper learning curve for developers new to the concept
- Can be overkill for simpler data manipulation tasks
Code Comparison
laravel-data:
class UserData extends Data
{
public function __construct(
public string $name,
public string $email,
public ?DateTime $birth_date
) {}
}
$userData = new UserData('John Doe', 'john@example.com', new DateTime('1990-01-01'));
laravel-collection-macros:
$users = collect([
['name' => 'John Doe', 'email' => 'john@example.com', 'birth_date' => '1990-01-01'],
]);
$formattedUsers = $users->extract(['name', 'email'])->toArray();
The laravel-data approach provides more structure and type safety, while laravel-collection-macros offers simpler, more flexible data manipulation for collections.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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:
composer require spatie/laravel-collection-macros
The package will automatically register itself.
Macros
after
at
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.
$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;
at
Retrieve an item at an index.
$data = new Collection([1, 2, 3]);
$data->at(0); // 1
$data->at(1); // 2
$data->at(-1); // 3
second
Retrieve item at the second index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->second(); // 2
third
Retrieve item at the third index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->third(); // 3
fourth
Retrieve item at the fourth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->fourth(); // 4
fifth
Retrieve item at the fifth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->fifth(); // 5
sixth
Retrieve item at the sixth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->sixth(); // 6
seventh
Retrieve item at the seventh index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->seventh(); // 7
eighth
Retrieve item at the eighth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->eighth(); // 8
ninth
Retrieve item at the ninth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->ninth(); // 9
tenth
Retrieve item at the tenth index.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data->tenth(); // 10
getNth
Retrieve item at the nth item.
$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
$data->getNth(11); // 11
before
Get 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;
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.
collect(['A', 'A', 'B', 'A'])->chunkBy(function($item) {
return $item == 'A';
}); // return Collection([['A', 'A'],['B'], ['A']])
collectBy
Get 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'])
containsAny
Will 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
containsAll
Will 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
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.
collect([1, 2, 3, 4])->eachCons(2); // return collect([[1, 2], [2, 3], [3, 4]])
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.
[$name, $role] = collect($user)->extract('name', 'role.name');
filterMap
Map 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]
firstOrFail
Get the first item. Throws Spatie\CollectionMacros\Exceptions\CollectionItemNotFound
if the item was not found.
$collection = collect([1, 2, 3, 4, 5, 6])->firstOrFail();
$collection->toArray(); // returns [1]
collect([])->firstOrFail(); // throws Spatie\CollectionMacros\Exceptions\CollectionItemNotFound
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.
$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]
fromPairs
Transform 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']
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.
$collection = collect([
'foo' => 'bar',
]);
$collection->getCaseInsensitive('Foo'); // returns 'bar';
glob
Returns a collection of a glob()
result.
Collection::glob('config/*.php');
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.
$posts->groupByModel('category');
// [
// [$categoryA, [/*...$posts*/]],
// [$categoryB, [/*...$posts*/]],
// ];
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.
$collection = collect([
'foo' => 'bar',
]);
$collection->hasCaseInsensitive('Foo'); // returns true;
head
Retrieves first item from the collection.
$collection = collect([1,2,3]);
$collection->head(); // return 1
$collection = collect([]);
$collection->head(); // return null
if
The 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 VALUE"
$collection = collect(['this is a value'])
->if(
fn(Collection $collection) => $collection->contains('this is a value'),
then: fn(Collection $collection) => $collection->map(fn(string $item) => strtoupper($item)),
else: fn(Collection $collection) => $collection->map(fn(string $item) => Str::kebab($item))
);
// the `else` closure will be executed
// the first element of the returned collection now contains "this-is-another-value"
$collection = collect(['this is another value'])
->if(
fn(Collection $collection) => $collection->contains('this is a value'),
then: fn(Collection $collection) => $collection->map(fn(string $item) => strtoupper($item)),
else: fn(Collection $collection) => $collection->map(fn(string $item) => Str::kebab($item))
);
ifAny
Executes 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';
});
ifEmpty
Executes 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';
});
insertAfter
Inserts 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]
insertAfterKey
Inserts an item after a given key and returns the updated Collection instance. Optionally a key for the new item can be given.
collect(['zero', 'two', 'three'])->insertAfterKey(0, 'one');
// Collection contains ['zero', 'one', 'two', 'three']
collect(['zero' => 0, 'two' => 2, 'three' => 3]->insertAfterKey('zero', 5, 'five');
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertAt
Inserts an item at a given index and returns the updated Collection instance. Optionally a key can be given.
collect(['zero', 'two', 'three'])->insertAt(1, 'one');
// Collection contains ['zero', 'one', 'two', 'three']
collect(['zero' => 0, 'two' => 2, 'three' => 3]->insertAt(1, 5, 'five');
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertBefore
Inserts an item before the first occurrence of a given item and returns the updated Collection instance. Optionally a key can be given.
collect(['zero', 'two', 'three'])->insertBefore('two', 'one');
// Collection contains ['zero', 'one', 'two', 'three']
collect(['zero' => 0, 'two' => 2, 'three' => 3]->insertBefore(2, 5, 'five');
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertBeforeKey
Inserts an item before a given key and returns the updated Collection instance. Optionally a key for the new item can be given.
collect(['zero', 'two', 'three'])->insertBeforeKey(1, 'one');
// Collection contains ['zero', 'one', 'two', 'three']
collect(['zero' => 0, 'two' => 2, 'three' => 3]->insertBeforeKey('two', 5, 'five');
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
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.
collect(['foo'])->none('bar'); // returns true
collect(['foo'])->none('foo'); // returns false
collect([['name' => 'foo']])->none('name', 'bar'); // returns true
collect([['name' => 'foo']])->none('name', 'foo'); // returns false
collect(['name' => 'foo'])->none(function ($key, $value) {
return $key === 'name' && $value === 'bar';
}); // returns true
paginate
Create a LengthAwarePaginator
instance for the items in the collection.
collect($posts)->paginate(5);
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.
paginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])
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.
$collection = new Collection([
'foo' => [
'bar' => [
'baz' => 'value',
]
]
]);
$collection->path('foo.bar.baz') // 'value'
pluckMany
Returns a collection with only the specified keys.
$collection = collect([
['a' => 1, 'b' => 10, 'c' => 100],
['a' => 2, 'b' => 20, 'c' => 200],
]);
$collection->pluckMany(['a', 'b']);
// returns
// collect([
// ['a' => 1, 'b' => 10],
// ['a' => 2, 'b' => 20],
// ]);
pluckManyValues
Returns a collection with only the specified keys' values.
$collection = collect([
['a' => 1, 'b' => 10, 'c' => 100],
['a' => 2, 'b' => 20, 'c' => 200],
]);
$collection->pluckMany(['a', 'b']);
// returns
// collect([
// [1, 10],
// [2, 20],
// ]);
pluckToArray
Returns array of values of a given key.
$collection = collect([
['a' => 1, 'b' => 10],
['a' => 2, 'b' => 20],
['a' => 3, 'b' => 30]
]);
$collection->pluckToArray('a'); // returns [1, 2, 3]
prioritize
Move elements to the start of the collection.
$collection = collect([
['id' => 1],
['id' => 2],
['id' => 3],
]);
$collection
->prioritize(function(array $item) {
return $item['id'] === 2;
})
->pluck('id')
->toArray(); // returns [2, 1, 3]
recursive
Convert an array and its children to collection using recursion.
collect([
'item' => [
'children' => []
]
])->recursive();
// subsequent arrays are now collections
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.
collect([
'item' => [
'children' => [
'one' => [1],
'two' => [2]
]
]
])->recursive(1); // Collection(['item' => Collection(['children' => ['one' => [1], 'two' => [2]]])])
This can be useful when you know that at a certain depth it'll not be necessary or that it may break your code.
collect([
'item' => [
'children' => [
'one' => [1],
'two' => [2]
]
]
])
->recursive(1)
->map(function ($item) {
return $item->map(function ($children) {
return $children->mapInto(Model::class);
});
}); // Collection(['item' => Collection(['children' => ['one' => Model(), 'two' => Model()]])])
// If we do not pass a max depth we will get the error "Argument #1 ($attributes) must be of type array"
rotate
Rotate the items in the collection with given offset
$collection = collect([1, 2, 3, 4, 5, 6]);
$rotate = $collection->rotate(1);
$rotate->toArray();
// [2, 3, 4, 5, 6, 1]
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.
$collection = collect([
['name' => 'Lesson 1', 'module' => 'Basics'],
['name' => 'Lesson 2', 'module' => 'Basics'],
['name' => 'Lesson 3', 'module' => 'Advanced'],
['name' => 'Lesson 4', 'module' => 'Advanced'],
['name' => 'Lesson 5', 'module' => 'Basics'],
]);
$collection->sectionBy('module');
// [
// ['Basics', [
// ['name' => 'Lesson 1', 'module' => 'Basics'],
// ['name' => 'Lesson 2', 'module' => 'Basics'],
// ]],
// ['Advanced', [
// ['name' => 'Lesson 3', 'module' => 'Advanced'],
// ['name' => 'Lesson 4', 'module' => 'Advanced'],
// ]],
// ['Basics', [
// ['name' => 'Lesson 5', 'module' => 'Basics'],
// ]],
// ];
Full signature: sectionBy($callback, $preserveKeys, $sectionKey, $itemsKey)
simplePaginate
Create a Paginator
instance for the items in the collection.
collect($posts)->simplePaginate(5);
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.
simplePaginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])
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.
collect([20, 51, 10, 50, 66])->sliceBefore(function($item) {
return $item > 50;
}); // return collect([[20],[51, 10, 50], [66])
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)
.
collect([1, 2, 3])->tail(); // return collect([2, 3])
toPairs
Transform a collection into an array with pairs.
$collection = collect(['a' => 'b', 'c' => 'd', 'e' => 'f'])->toPairs();
$collection->toArray(); // returns ['a', 'b'], ['c', 'd'], ['e', 'f']
transpose
The goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.
collect([
['Jane', 'Bob', 'Mary'],
['jane@example.com', 'bob@example.com', 'mary@example.com'],
['Doctor', 'Plumber', 'Dentist'],
])->transpose()->toArray();
// [
// ['Jane', 'jane@example.com', 'Doctor'],
// ['Bob', 'bob@example.com', 'Plumber'],
// ['Mary', 'mary@example.com', 'Dentist'],
// ]
try
If any of the methods between try
and catch
throw an exception, then the exception can be handled in catch
.
collect(['a', 'b', 'c', 1, 2, 3])
->try()
->map(fn ($letter) => strtoupper($letter))
->each(function() {
throw new Exception('Explosions in the sky');
})
->catch(function (Exception $exception) {
// handle exception here
})
->map(function() {
// further operations can be done, if the exception wasn't rethrow in the `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.
$collection = collect(['a', 'b', 'c', 1, 2, 3])
->try()
->map(function ($item) {
throw new Exception();
})
->catch(function (Exception $exception, $collection) {
return collect(['d', 'e', 'f']);
})
->map(function ($item) {
return strtoupper($item);
});
// ['D', 'E', 'F']
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.
collect(['foo', 'foo'])->validate(function ($item) {
return $item === 'foo';
}); // returns true
collect(['sebastian@spatie.be', 'bla'])->validate('email'); // returns false
collect(['sebastian@spatie.be', 'freek@spatie.be'])->validate('email'); // returns true
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.
// pass the field name that should be used as a weight
$randomItem = collect([
['value' => 'a', 'weight' => 30],
['value' => 'b', 'weight' => 20],
['value' => 'c', 'weight' => 10],
])->weightedRandom('weight');
Alternatively, you can pass a callable to get the weight.
$randomItem = collect([
['value' => 'a', 'weight' => 30],
['value' => 'b', 'weight' => 20],
['value' => 'c', 'weight' => 10],
])->weightedRandom(function(array $item) {
return $item['weight'];
});
withSize
Create a new collection with the specified amount of items.
Collection::withSize(1)->toArray(); // return [1];
Collection::withSize(5)->toArray(); // return [1,2,3,4,5];
Changelog
Please see CHANGELOG for more information what has changed recently.
Testing
$ composer test
Contributing
Please see CONTRIBUTING for details.
Security
If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.
Credits
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.
Top Related Projects
The Laravel Framework.
A Collections-only split from Laravel's Illuminate Support
⚡️ Laravel components that take care of one specific task
Easily build Eloquent queries from API requests
Powerful data objects for Laravel
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot