PHPackages                             code-distortion/laravel-collection-macros - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. code-distortion/laravel-collection-macros

ActiveLibrary

code-distortion/laravel-collection-macros
=========================================

A set of useful Laravel collection macros - a spatie/laravel-collection-macros fork

7.0.3(5y ago)014MITPHPPHP ^7.4

Since Jul 26Pushed 5y agoCompare

[ Source](https://github.com/code-distortion/laravel-collection-macros)[ Packagist](https://packagist.org/packages/code-distortion/laravel-collection-macros)[ Docs](https://github.com/spatie/laravel-collection-macros)[ RSS](/packages/code-distortion-laravel-collection-macros/feed)WikiDiscussions custom Synced today

READMEChangelogDependencies (8)Versions (57)Used By (0)

A set of useful Laravel collection macros
=========================================

[](#a-set-of-useful-laravel-collection-macros)

[![Latest Version on Packagist](https://camo.githubusercontent.com/042e6d05ba8850b8cbb7ed1cf4143e49e36034c3f8eabfd001471cddd6704d7e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64652d646973746f7274696f6e2f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/code-distortion/laravel-collection-macros)[![PHP from Packagist](https://camo.githubusercontent.com/2e1ec69f5f8b71261f0f3d85024dceae1f9715d0a9ec2cbc9f7fcb4bd366e3ab/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f636f64652d646973746f7274696f6e2f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f733f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/2e1ec69f5f8b71261f0f3d85024dceae1f9715d0a9ec2cbc9f7fcb4bd366e3ab/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f636f64652d646973746f7274696f6e2f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f733f7374796c653d666c61742d737175617265)[![Laravel](https://camo.githubusercontent.com/3c9d0ace19ae77890c90fcf3cd6dbb2c01d58fc879d101242df7429704bd7de1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d37253230253236253230382d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/3c9d0ace19ae77890c90fcf3cd6dbb2c01d58fc879d101242df7429704bd7de1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d37253230253236253230382d626c75653f7374796c653d666c61742d737175617265)[![GitHub Workflow Status](https://camo.githubusercontent.com/7c303b2752dcc579040dd1b90b5244a42696f200f388b03c719960e86b436ce7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f636f64652d646973746f7274696f6e2f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732f72756e2d74657374733f6c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/code-distortion/laravel-collection-macros/actions)

This package is a fork of [spatie/laravel-collection-macros](https://github.com/spatie/laravel-collection-macros). It contains a subset of the original macros as well as a few extra ones.

This package is intended for PERSONAL USE. Please see the original Spatie package if you would like to submit a PR or request a feature.

Installation
------------

[](#installation)

Install the package via composer:

```
composer require code-distortion/laravel-collection-macros
```

The package will automatically register itself.

Macros
------

[](#macros)

Macros kept from the original spatie package:

- [`catch`](#catch)
- [`extract`](#extract)
- [`glob`](#glob)
- [`ifAny`](#ifany)
- [`ifEmpty`](#ifempty)
- [`none`](#none)
- [`paginate`](#paginate)
- [`prioritize`](#prioritize)
- [`simplePaginate`](#simplepaginate)
- [`try`](#try)
- [`transpose`](#transpose)
- [`validate`](#validate)

New macros added:

- [`keepValues`](#keepvalues)
- [`keyedKeys`](#keyedkeys)
- [`rejectValues`](#rejectvalues)

### `catch`

[](#catch)

See [`Try`](#try)

### `extract`

[](#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');
```

### `glob`

[](#glob)

Returns a collection of a `glob()` result.

```
Collection::glob('config/*.php');
```

### `ifAny`

[](#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`

[](#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';
});
```

### `keepValues`

[](#keepvalues)

Returns a collection containing only values that were in the given list.

```
collect(['foo', 'bar'])->keepValues(['foo'])->toArray(); // ['foo']
```

`keepValues` accepts a second parameter to turn strict-comparisons on (default *false*).

```
collect(['123', 456])->keepValues(['123', '456'], true)->toArray(); // ['123']
```

### `keyedKeys`

[](#keyedkeys)

Returns a collection where the values are the same as the keys.

```
collect(['foo' => 1, 'bar' => 2])->keyedKeys()->toArray(); // ['foo' => 'foo', 'bar' => 'bar']
```

### `none`

[](#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`

[](#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](https://laravel.com/docs/5.4/pagination) for an in-depth guide.

```
paginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])

```

### `prioritize`

[](#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]
```

### `rejectValues`

[](#rejectvalues)

Removes the given values from the collection.

```
collect(['foo', 'bar'])->rejectValues(['foo'])->toArray(); // ['bar']
```

`rejectValues` accepts a second parameter to turn strict-comparisons on (default *false*).

```
collect(['123', 456])->rejectValues(['123', '456'], true)->toArray(); // [456]
```

### `simplePaginate`

[](#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](https://laravel.com/docs/5.4/pagination) 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](https://laravel.com/docs/5.4/pagination).

### `try`

[](#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']
```

### `transpose`

[](#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'],
// ]
```

### `validate`

[](#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
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Contributions are not being sought for this package. Please see the original [spatie/laravel-collection-macros](https://github.com/spatie/laravel-collection-macros) package if you would like to contribute.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [Tim Chandler](https://github.com/code-distortion) (fork)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

33

—

LowBetter than 74% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~28 days

Recently: every ~22 days

Total

55

Last Release

2068d ago

Major Versions

3.8.1 → 4.0.02018-08-27

4.3.1 → 5.0.02019-02-27

4.3.2 → 5.0.12019-03-07

5.0.2 → 6.0.02019-09-04

v6.x-dev → 7.0.02020-06-11

PHP version history (4 changes)0.0.1PHP ^7.0

4.0.0PHP ^7.1

5.0.0PHP ^7.2

7.0.0PHP ^7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/5c2faa0204914f71abdbae72c3c12b86fb33a1dce0254e592109411a5b4689a3?d=identicon)[code-distortion](/maintainers/code-distortion)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (142 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (88 commits)")[![basepack](https://avatars.githubusercontent.com/u/939500?v=4)](https://github.com/basepack "basepack (9 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (8 commits)")[![mdrost](https://avatars.githubusercontent.com/u/4083346?v=4)](https://github.com/mdrost "mdrost (7 commits)")[![vv12131415](https://avatars.githubusercontent.com/u/17382248?v=4)](https://github.com/vv12131415 "vv12131415 (4 commits)")[![jstoone](https://avatars.githubusercontent.com/u/1711456?v=4)](https://github.com/jstoone "jstoone (4 commits)")[![chapeupreto](https://avatars.githubusercontent.com/u/834048?v=4)](https://github.com/chapeupreto "chapeupreto (4 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (3 commits)")[![assertchris](https://avatars.githubusercontent.com/u/200609?v=4)](https://github.com/assertchris "assertchris (3 commits)")[![code-distortion](https://avatars.githubusercontent.com/u/56794290?v=4)](https://github.com/code-distortion "code-distortion (3 commits)")[![joshwhatk](https://avatars.githubusercontent.com/u/1848905?v=4)](https://github.com/joshwhatk "joshwhatk (3 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (3 commits)")[![gzhihao](https://avatars.githubusercontent.com/u/2484532?v=4)](https://github.com/gzhihao "gzhihao (2 commits)")[![gizburdt](https://avatars.githubusercontent.com/u/1470623?v=4)](https://github.com/gizburdt "gizburdt (2 commits)")[![m1guelpf](https://avatars.githubusercontent.com/u/23558090?v=4)](https://github.com/m1guelpf "m1guelpf (1 commits)")[![morloderex](https://avatars.githubusercontent.com/u/5677808?v=4)](https://github.com/morloderex "morloderex (1 commits)")[![repat](https://avatars.githubusercontent.com/u/516807?v=4)](https://github.com/repat "repat (1 commits)")[![aguimaraes](https://avatars.githubusercontent.com/u/131234?v=4)](https://github.com/aguimaraes "aguimaraes (1 commits)")[![CheatCodes](https://avatars.githubusercontent.com/u/4729881?v=4)](https://github.com/CheatCodes "CheatCodes (1 commits)")

---

Tags

spatielaravel-collection-macros

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/code-distortion-laravel-collection-macros/health.svg)

```
[![Health](https://phpackages.com/badges/code-distortion-laravel-collection-macros/health.svg)](https://phpackages.com/packages/code-distortion-laravel-collection-macros)
```

###  Alternatives

[spatie/laravel-activitylog

A very simple activity logger to monitor the users of your website or application

5.8k45.4M309](/packages/spatie-laravel-activitylog)[spatie/laravel-backup

A Laravel package to backup your application

6.0k21.8M186](/packages/spatie-laravel-backup)[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M219](/packages/spatie-laravel-query-builder)[spatie/laravel-collection-macros

A set of useful Laravel collection macros

1.9k5.7M29](/packages/spatie-laravel-collection-macros)[spatie/laravel-sitemap

Create and generate sitemaps with ease

2.6k14.6M107](/packages/spatie-laravel-sitemap)[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
