PHPackages                             pulli/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. [Utility &amp; Helpers](/categories/utility)
4. /
5. pulli/laravel-collection-macros

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

pulli/laravel-collection-macros
===============================

Package for some custom collection macros.

v1.4.3(2mo ago)0996↓33.3%[2 PRs](https://github.com/the-pulli/laravel-collection-macros/pulls)MITPHPPHP ^8.4CI passing

Since Dec 28Pushed 2mo agoCompare

[ Source](https://github.com/the-pulli/laravel-collection-macros)[ Packagist](https://packagist.org/packages/pulli/laravel-collection-macros)[ Docs](https://github.com/the-pulli/laravel-collection-macros)[ GitHub Sponsors](https://github.com/the-pulli)[ RSS](/packages/pulli-laravel-collection-macros/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (24)Versions (11)Used By (0)

Useful Laravel collection macros
================================

[](#useful-laravel-collection-macros)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c72c22cd66d5312b7f40dd7f33df6b38a5dae19dfbed0cfde6087c9fcd1d0a11/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70756c6c692f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pulli/laravel-collection-macros)[![GitHub Tests Action Status](https://camo.githubusercontent.com/b46d1f647eae142576d9bc41b0c1cb472385e32727dc0c7f62584b7495871b5d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468652d70756c6c692f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/the-pulli/laravel-collection-macros/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/e9dc734d99a3125779b0e8d7d7648a5ba7ddcd459a3f06591666961b4c53d7dc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468652d70756c6c692f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/the-pulli/laravel-collection-macros/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![PHPStan](https://camo.githubusercontent.com/e15585b17e16e64ed1b966df4dd89ecafb88dbe8e687e6edc1b5c1fe7c6c93e1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468652d70756c6c692f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d7068707374616e267374796c653d666c61742d737175617265)](https://github.com/the-pulli/laravel-collection-macros/actions?query=workflow%3Aphpstan+branch%3Amain)[![codecov](https://camo.githubusercontent.com/8cb69a797ffe799e112fa5a1de1041ef1054e5074aaf845b04de84308547c47e/68747470733a2f2f636f6465636f762e696f2f67682f7468652d70756c6c692f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732f67726170682f62616467652e737667)](https://codecov.io/gh/the-pulli/laravel-collection-macros)[![Total Downloads](https://camo.githubusercontent.com/95886c9a2fa7882ec1c18e70b809de7a8d22aee978ed6f13f358c6f9bad2fd1e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f70756c6c692f6c61726176656c2d636f6c6c656374696f6e2d6d6163726f732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pulli/laravel-collection-macros)

Contains some handy collection macros.

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

[](#installation)

You can install the package via composer:

```
composer require pulli/laravel-collection-macros
```

You can publish the service provider via:

```
php artisan vendor:publish --tag="pulli-collection-macros-provider"
```

You can publish the config file with:

```
php artisan vendor:publish --tag="pulli-collection-macros-config"
```

This is the contents of the published config file:

```
return [
    'auto-update' => true,
];
```

Usage
-----

[](#usage)

### Macros

[](#macros)

- [`compareCount`](#comparecount)
- [`even`](#even)
- [`explode`](#explode)
- [`firstAndLast`](#firstandlast)
- [`firstAndLastKey`](#firstandlastkey)
- [`implodeToStringable`](#implodetostringable)
- [`joinToStringable`](#jointostringable)
- [`mapToCollection`](#maptocollection)
- [`mapToCollectionFrom`](#maptocollectionfrom)
- [`odd`](#odd)
- [`onlyInts`](#onlyints)
- [`onlyStrings`](#onlystrings)
- [`positive`](#positive)
- [`recursiveToArray`](#recursivetoarray)
- [`recursiveToArrayFrom`](#recursivetoarrayfrom)

#### `compareCount`

[](#comparecount)

Compares the count of the collection with another countable and optionally zips them together. Throws an `InvalidArgumentException` if counts don't match.

```
compareCount(mixed $countable, bool $shouldZip = true): Collection
```

ParameterTypeDefaultDescription`$countable`mixedrequiredAn array, Countable, or object with count() method`$shouldZip`bool`true`When true, returns zipped collection; when false, returns original```
$collection = Collection::make(['a', 'b'])->compareCount([1, 2]);
// returns [['a', 1], ['b', 2]]

$collection = Collection::make(['a', 'b'])->compareCount([1, 2], shouldZip: false);
// returns ['a', 'b']

Collection::make(['a', 'b'])->compareCount([1, 2, 3]);
// throws InvalidArgumentException: Count of input mismatch with given collection.
```

#### `even`

[](#even)

Filters the collection to only integer values and returns the even ones.

```
even(bool $preserveKeys = false): Collection
```

ParameterTypeDefaultDescription`$preserveKeys`bool`false`Whether to preserve original array keys```
$collection = Collection::range(0, 6)->even();
// returns [0, 2, 4, 6]

$collection = Collection::range(0, 6)->even(preserveKeys: true);
// returns [0 => 0, 2 => 2, 4 => 4, 6 => 6]
```

#### `explode`

[](#explode)

Creates a collection from an exploded string. Uses the same signature as PHP's native `explode()` function.

```
Collection::explode(string $separator, string $string, int $limit = PHP_INT_MAX): Collection
```

ParameterTypeDefaultDescription`$separator`stringrequiredThe delimiter string`$string`stringrequiredThe input string to split`$limit`int`PHP_INT_MAX`Maximum number of elements```
$collection = Collection::explode(';', 'Twenty;Banana;Boats');
// returns ['Twenty', 'Banana', 'Boats']

$collection = Collection::explode(';', 'Twenty;Banana;Boats', 2);
// returns ['Twenty', 'Banana;Boats']

$collection = Collection::explode(';', 'Twenty;Banana;Boats', -1);
// returns ['Twenty', 'Banana']
```

#### `firstAndLast`

[](#firstandlast)

Returns the first and last element of the collection as an array.

```
firstAndLast(
    ?callable $first = null,
    mixed $firstDefault = null,
    ?callable $last = null,
    mixed $lastDefault = null
): array
```

ParameterTypeDefaultDescription`$first`callable|null`null`Optional callback to find the first element`$firstDefault`mixed`null`Default value if first element not found`$last`callable|null`null`Optional callback to find the last element`$lastDefault`mixed`null`Default value if last element not found```
[$first, $last] = Collection::make(['Jane', 'John', 'Joe'])->firstAndLast();
// $first = 'Jane', $last = 'Joe'

[$first, $last] = Collection::range(0, 6)->firstAndLast(
    first: fn ($value) => $value > 0,
    last: fn ($value) => $value < 6,
);
// $first = 1, $last = 5
```

#### `firstAndLastKey`

[](#firstandlastkey)

Returns the first and last key of the collection as an array.

```
firstAndLastKey(
    ?callable $first = null,
    mixed $firstDefault = null,
    ?callable $last = null,
    mixed $lastDefault = null
): array
```

ParameterTypeDefaultDescription`$first`callable|null`null`Optional callback to find the first key`$firstDefault`mixed`null`Default value if first key not found`$last`callable|null`null`Optional callback to find the last key`$lastDefault`mixed`null`Default value if last key not found```
[$first, $last] = Collection::make(['Jane', 'John', 'Joe'])->firstAndLastKey();
// $first = 0, $last = 2

[$first, $last] = Collection::range(0, 6)->firstAndLastKey(
    first: fn ($value) => $value > 0,
    last: fn ($value) => $value < 6,
);
// $first = 1, $last = 5
```

#### `implodeToStringable`

[](#implodetostringable)

Implodes the collection and returns it as a Stringable object.

```
implodeToStringable(callable|string|null $value, ?string $glue = null): Stringable
```

ParameterTypeDefaultDescription`$value`callable|string|nullrequiredThe key to implode or a callback`$glue`string|null`null`The glue string between elements```
$stringable = Collection::make(['Jane', 'John'])->implodeToStringable(', ');
// Stringable of "Jane, John"

$stringable = Collection::make([
    ['name' => 'Jane'],
    ['name' => 'John'],
])->implodeToStringable('name', ', ');
// Stringable of "Jane, John"
```

#### `joinToStringable`

[](#jointostringable)

Joins the collection and returns it as a Stringable object.

```
joinToStringable(string $glue, string $finalGlue = ''): Stringable
```

ParameterTypeDefaultDescription`$glue`stringrequiredThe glue string between elements`$finalGlue`string`''`The glue string before the last element```
$stringable = Collection::make(['Jane', 'John', 'Jack'])->joinToStringable(', ');
// Stringable of "Jane, John, Jack"

$stringable = Collection::make(['Jane', 'John', 'Jack'])->joinToStringable(', ', ' and ');
// Stringable of "Jane, John and Jack"
```

#### `mapToCollection`

[](#maptocollection)

Recursively maps all arrays/objects to nested Collection objects.

```
mapToCollection(array $ary = [], bool $deep = false): Collection
```

ParameterTypeDefaultDescription`$ary`array`[]`Additional array to merge`$deep`bool`false`When true, also converts Arrayable objects recursively```
$collection = Collection::make([['test' => 1], 2, 3])->mapToCollection();
$collection->get(0)->get('test'); // returns 1

// With additional data to merge
$collection = Collection::make([['a' => 1]])->mapToCollection(['b' => 2]);

// With deep conversion of Arrayable objects
$collection = Collection::make([$item1, $item2])->mapToCollection(deep: true);
```

#### `mapToCollectionFrom`

[](#maptocollectionfrom)

Static method to recursively map all arrays/objects to nested Collection objects.

```
Collection::mapToCollectionFrom(array $ary, bool $deep = false, int $maxDepth = 512): Collection
```

ParameterTypeDefaultDescription`$ary`arrayrequiredThe array to convert`$deep`bool`false`When true, also converts Arrayable objects recursively`$maxDepth`int`512`Maximum recursion depth to prevent stack overflow```
$collection = Collection::mapToCollectionFrom([['test' => 1], 2, 3]);
$collection->get(0)->get('test'); // returns 1

// With deep conversion of Arrayable objects
$collection = Collection::mapToCollectionFrom([$item1, $item2], deep: true);
```

#### `odd`

[](#odd)

Filters the collection to only integer values and returns the odd ones.

```
odd(bool $preserveKeys = false): Collection
```

ParameterTypeDefaultDescription`$preserveKeys`bool`false`Whether to preserve original array keys```
$collection = Collection::range(0, 6)->odd();
// returns [1, 3, 5]

$collection = Collection::range(0, 6)->odd(preserveKeys: true);
// returns [1 => 1, 3 => 3, 5 => 5]
```

#### `onlyInts`

[](#onlyints)

Filters the collection to only integer values.

```
onlyInts(bool $preserveKeys = false): Collection
```

ParameterTypeDefaultDescription`$preserveKeys`bool`false`Whether to preserve original array keys```
$collection = Collection::make([0, 'Donkey Kong', 6, new stdClass])->onlyInts();
// returns [0, 6]

$collection = Collection::make([0, 'Donkey Kong', 6, new stdClass])->onlyInts(preserveKeys: true);
// returns [0 => 0, 2 => 6]

$collection = Collection::make([-5, 1.5, 3, '4'])->onlyInts();
// returns [-5, 3] (floats and numeric strings are excluded)
```

#### `onlyStrings`

[](#onlystrings)

Filters the collection to only string values, optionally converting Stringable objects.

```
onlyStrings(bool $strict = false, bool $preserveKeys = false): Collection
```

ParameterTypeDefaultDescription`$strict`bool`false`When true, only accepts native strings; when false, also converts Stringable objects`$preserveKeys`bool`false`Whether to preserve original array keys```
$collection = Collection::make([0, 'Donkey Kong', 6, 'Bananas'])->onlyStrings();
// returns ['Donkey Kong', 'Bananas']

// With Stringable objects (non-strict mode converts them)
$collection = Collection::make(['Hello', new StringableObject()])->onlyStrings();
// returns ['Hello', 'StringableValue']

// Strict mode rejects Stringable objects
$collection = Collection::make(['Hello', new StringableObject()])->onlyStrings(strict: true);
// returns ['Hello']

// Preserve original keys
$collection = Collection::make(['a' => 'Hello', 'b' => 123, 'c' => 'World'])
    ->onlyStrings(preserveKeys: true);
// returns ['a' => 'Hello', 'c' => 'World']
```

#### `positive`

[](#positive)

Returns true if the collection is not empty (has at least one element).

```
positive(): bool
```

```
Collection::make([1, 2, 3])->positive(); // returns true
Collection::make()->positive();          // returns false
```

#### `recursiveToArray`

[](#recursivetoarray)

Recursively converts all nested objects with `toArray()` to arrays.

```
recursiveToArray(array $ary = []): array
```

ParameterTypeDefaultDescription`$ary`array`[]`Additional array to merge```
// Objects with toArray() method are recursively converted
$array = Collection::make(['item1' => $object1, 'item2' => $object2])->recursiveToArray();

// With additional data to merge
$array = Collection::make(['a' => $object])->recursiveToArray(['b' => $object2]);
```

#### `recursiveToArrayFrom`

[](#recursivetoarrayfrom)

Static method to recursively convert all nested objects with `toArray()` to arrays.

```
Collection::recursiveToArrayFrom(array $ary, int $maxDepth = 512): array
```

ParameterTypeDefaultDescription`$ary`arrayrequiredThe array to convert`$maxDepth`int`512`Maximum recursion depth to prevent stack overflow```
// Objects with toArray() method are recursively converted
$array = Collection::recursiveToArrayFrom(['item1' => $object1, 'item2' => $object2]);
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [PuLLi](https://github.com/the-pulli)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance88

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90.9% of commits — single point of failure

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 ~11 days

Recently: every ~19 days

Total

8

Last Release

60d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c14e16040b5b84e5c91af8c7a39480567d951bfc27673f97d9c75480dbe20b5e?d=identicon)[pulli](/maintainers/pulli)

---

Top Contributors

[![the-pulli](https://avatars.githubusercontent.com/u/112799107?v=4)](https://github.com/the-pulli "the-pulli (20 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravelmacroscollection-macros

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-livewire-wizard

Build wizards using Livewire

4061.0M4](/packages/spatie-laravel-livewire-wizard)[nativephp/mobile

NativePHP for Mobile

82724.0k43](/packages/nativephp-mobile)[tonysm/importmap-laravel

Use ESM with importmap to manage modern JavaScript in Laravel without transpiling or bundling.

148399.8k1](/packages/tonysm-importmap-laravel)[laracraft-tech/laravel-useful-additions

A collection of useful Laravel additions!

58109.4k](/packages/laracraft-tech-laravel-useful-additions)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

123544.7k](/packages/worksome-exchange)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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