{"id":13396043,"url":"https://github.com/spatie/laravel-collection-macros","last_synced_at":"2025-05-12T13:16:46.314Z","repository":{"id":38205975,"uuid":"64222176","full_name":"spatie/laravel-collection-macros","owner":"spatie","description":"A set of useful Laravel collection macros","archived":false,"fork":false,"pushed_at":"2025-04-22T07:35:06.000Z","size":399,"stargazers_count":1835,"open_issues_count":0,"forks_count":143,"subscribers_count":29,"default_branch":"main","last_synced_at":"2025-05-12T13:16:25.960Z","etag":null,"topics":["collection","hacktoberfest","laravel","macros","php"],"latest_commit_sha":null,"homepage":"https://freek.dev/540-some-handy-collection-macros","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"spatie"}},"created_at":"2016-07-26T13:10:12.000Z","updated_at":"2025-05-10T16:28:01.000Z","dependencies_parsed_at":"2023-01-25T08:30:35.702Z","dependency_job_id":"585b8d44-9d38-4d0a-9f81-b2a71c3dbfab","html_url":"https://github.com/spatie/laravel-collection-macros","commit_stats":{"total_commits":348,"total_committers":62,"mean_commits":5.612903225806452,"dds":0.5344827586206897,"last_synced_commit":"5f33d949912a3e8de7598dc6fbff6b3d3a5c5021"},"previous_names":[],"tags_count":79,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-collection-macros","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-collection-macros/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-collection-macros/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-collection-macros/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/laravel-collection-macros/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745196,"owners_count":21957319,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["collection","hacktoberfest","laravel","macros","php"],"created_at":"2024-07-30T18:00:38.271Z","updated_at":"2025-05-12T13:16:46.276Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://github.com/sponsors/spatie"],"categories":["Popular Packages","PHP"],"sub_categories":[],"readme":"\u003cdiv align=\"left\"\u003e\n    \u003ca href=\"https://spatie.be/open-source?utm_source=github\u0026utm_medium=banner\u0026utm_campaign=laravel-collection-macros\"\u003e\n      \u003cpicture\u003e\n        \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://spatie.be/packages/header/laravel-collection-macros/html/dark.webp\"\u003e\n        \u003cimg alt=\"Logo for laravel-collection-macros\" src=\"https://spatie.be/packages/header/laravel-collection-macros/html/light.webp\" height=\"190\"\u003e\n      \u003c/picture\u003e\n    \u003c/a\u003e\n\n\u003ch1\u003eA set of useful Laravel collection macros\u003c/h1\u003e\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-collection-macros.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-collection-macros)\n![Run tests](https://github.com/spatie/laravel-collection-macros/workflows/Run%20tests/badge.svg)\n![Check \u0026 fix styling](https://github.com/spatie/laravel-collection-macros/workflows/Check%20\u0026%20fix%20styling/badge.svg)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-collection-macros.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-collection-macros)\n    \n\u003c/div\u003e\n\nThis repository contains some useful collection macros.\n\nSpatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/laravel-collection-macros.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/laravel-collection-macros)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe 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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Installation\n\nYou can pull in the package via composer:\n\n``` bash\ncomposer require spatie/laravel-collection-macros\n```\n\nThe package will automatically register itself.\n\n## Macros\n\n- [`after`](#after)\n- [`at`](#at)\n    - [`second`](#second)\n    - [`third`](#third)\n    - [`fourth`](#fourth)\n    - [`fifth`](#fifth)\n    - [`sixth`](#sixth)\n    - [`seventh`](#seventh)\n    - [`eighth`](#eighth)\n    - [`ninth`](#ninth)\n    - [`tenth`](#tenth)\n    - [`getNth`](#getNth)\n- [`catch`](#catch)\n- [`chunkBy`](#chunkby)\n- [`collectBy`](#collectBy)\n- [`containsAny`](#containsAny)\n- [`containsAll`](#containsAll)\n- [`eachCons`](#eachcons)\n- [`extract`](#extract)\n- [`filterMap`](#filtermap)\n- [`firstOrFail`](#firstorfail)\n- [`firstOrPush`](#firstorpush)\n- [`fromPairs`](#frompairs)\n- [`getCaseInsensitive`](#getcaseinsensitive)\n- [`glob`](#glob)\n- [`groupByModel`](#groupbymodel)\n- [`hasCaseInsensitive`](#hascaseinsensitive)\n- [`head`](#head)\n- [`if`](#if)\n- [`ifAny`](#ifany)\n- [`ifEmpty`](#ifempty)\n- [`insertAfter`](#insertafter)\n- [`insertAfterKey`](#insertafterkey)\n- [`insertAt`](#insertat)\n- [`insertBefore`](#insertbefore)\n- [`insertBeforeKey`](#insertbeforekey)\n- [`none`](#none)\n- [`paginate`](#paginate)\n- [`path`](#path)\n- [`pluckMany`](#pluckmany)\n- [`pluckManyValues`](#pluckmanyvalues)\n- [`pluckToArray`](#plucktoarray)\n- [`prioritize`](#prioritize)\n- [`recursive`](#recursive)\n- [`rotate`](#rotate)\n- [`sectionBy`](#sectionby)\n- [`simplePaginate`](#simplepaginate)\n- [`sliceBefore`](#slicebefore)\n- [`tail`](#tail)\n- [`try`](#try)\n- [`toPairs`](#topairs)\n- [`transpose`](#transpose)\n- [`validate`](#validate)\n- [`weightedRandom`](#weightedRandom)\n- [`withSize`](#withsize)\n\n### `after`\n\nGet the next item from the collection.\n\n```php\n$collection = collect([1,2,3]);\n\n$currentItem = 2;\n\n$currentItem = $collection-\u003eafter($currentItem); // return 3;\n$collection-\u003eafter($currentItem); // return null;\n\n$currentItem = $collection-\u003eafter(function($item) {\n    return $item \u003e 1;\n}); // return 3;\n```\n\nYou can also pass a second parameter to be used as a fallback.\n\n```php\n$collection = collect([1,2,3]);\n\n$currentItem = 3;\n\n$collection-\u003eafter($currentItem, $collection-\u003efirst()); // return 1;\n```\n\n### `at`\n\nRetrieve an item at an index.\n\n```php\n$data = new Collection([1, 2, 3]);\n\n$data-\u003eat(0); // 1\n$data-\u003eat(1); // 2\n$data-\u003eat(-1); // 3\n```\n\n### `second`\nRetrieve item at the second index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003esecond(); // 2\n```\n\n### `third`\nRetrieve item at the third index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003ethird(); // 3\n```\n\n### `fourth`\nRetrieve item at the fourth index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003efourth(); // 4\n```\n\n### `fifth`\nRetrieve item at the fifth index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003efifth(); // 5\n```\n\n### `sixth`\nRetrieve item at the sixth index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003esixth(); // 6\n```\n\n### `seventh`\nRetrieve item at the seventh index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003eseventh(); // 7\n```\n\n### `eighth`\nRetrieve item at the eighth index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003eeighth(); // 8\n```\n\n### `ninth`\nRetrieve item at the ninth index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003eninth(); // 9\n```\n\n### `tenth`\nRetrieve item at the tenth index.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);\n\n$data-\u003etenth(); // 10\n```\n\n### `getNth`\nRetrieve item at the nth item.\n\n```php\n$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);\n\n$data-\u003egetNth(11); // 11\n```\n\n### `before`\n\nGet the previous item from the collection.\n\n```php\n$collection = collect([1,2,3]);\n\n$currentItem = 2;\n\n$currentItem = $collection-\u003ebefore($currentItem); // return 1;\n$collection-\u003ebefore($currentItem); // return null;\n\n$currentItem = $collection-\u003ebefore(function($item) {\n    return $item \u003e 2;\n}); // return 2;\n```\n\nYou can also pass a second parameter to be used as a fallback.\n\n```php\n$collection = collect([1,2,3]);\n\n$currentItem = 1;\n\n$collection-\u003ebefore($currentItem, $collection-\u003elast()); // return 3;\n```\n\n### `catch`\n\nSee [`Try`](#try)\n\n### `chunkBy`\n\nChunks 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.\n\n```php\ncollect(['A', 'A', 'B', 'A'])-\u003echunkBy(function($item) {\n    return $item == 'A';\n}); // return Collection([['A', 'A'],['B'], ['A']])\n```\n\n### `collectBy`\n\nGet an item at a given key, and collect it.\n\n```php\n$collection = collect([\n    'foo' =\u003e [1, 2, 3],\n    'bar' =\u003e [4, 5, 6],\n]);\n\n$collection-\u003ecollectBy('foo'); // Collection([1, 2, 3])\n```\n\nYou can also pass a second parameter to be used as a fallback.\n\n```php\n$collection = collect([\n    'foo' =\u003e [1, 2, 3],\n    'bar' =\u003e [4, 5, 6],\n]);\n\n$collection-\u003ecollectBy('baz', ['Nope']); // Collection(['Nope'])\n```\n\n### `containsAny`\n\nWill return `true` if one or more of the given values exist in the collection.\n\n```php\n$collection = collect(['a', 'b', 'c']);\n\n$collection-\u003econtainsAny(['b', 'c', 'd']); // returns true\n$collection-\u003econtainsAny(['c', 'd', 'e']); // returns true\n$collection-\u003econtainsAny(['d', 'e', 'f']); // returns false\n$collection-\u003econtainsAny([]); // returns false\n```\n\n### `containsAll`\n\nWill return `true` if all given values exist in the collection.\n\n```php\n$collection = collect(['a', 'b', 'c']);\n\n$collection-\u003econtainsAll(['b', 'c',]); // returns true\n$collection-\u003econtainsAll(['c', 'd']); // returns false\n$collection-\u003econtainsAll(['d', 'e']); // returns false\n$collection-\u003econtainsAll([]); // returns true\n```\n\n### `eachCons`\n\nGet 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.\n\n```php\ncollect([1, 2, 3, 4])-\u003eeachCons(2); // return collect([[1, 2], [2, 3], [3, 4]])\n```\n\n### `extract`\n\nExtract keys from a collection. This is very similar to `only`, with two key differences:\n\n- `extract` returns an array of values, not an associative array\n- If a value doesn't exist, it will fill the value with `null` instead of omitting it\n\n`extract` is useful when using PHP 7.1 short `list()` syntax.\n\n```php\n[$name, $role] = collect($user)-\u003eextract('name', 'role.name');\n```\n\n### `filterMap`\n\nMap a collection and remove falsy values in one go.\n\n```php\n$collection = collect([1, 2, 3, 4, 5, 6])-\u003efilterMap(function ($number) {\n    $quotient = $number / 3;\n\n    return is_integer($quotient) ? $quotient : null;\n});\n\n$collection-\u003etoArray(); // returns [1, 2]\n```\n\n### `firstOrFail`\n\nGet the first item. Throws `Spatie\\CollectionMacros\\Exceptions\\CollectionItemNotFound` if the item was not found.\n\n```php\n$collection = collect([1, 2, 3, 4, 5, 6])-\u003efirstOrFail();\n\n$collection-\u003etoArray(); // returns [1]\n\ncollect([])-\u003efirstOrFail(); // throws Spatie\\CollectionMacros\\Exceptions\\CollectionItemNotFound\n```\n\n### `firstOrPush`\n\nRetrieve the first item using the callable given as the first parameter. If no value exists, push the value of the second\nparameter into the collection. You can pass a callable as the second parameter.\n\nThis 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.\n\n```php\n$collection = collect([1, 2, 3])-\u003efirstOrPush(fn($item) =\u003e $item === 4, 4);\n\n$collection-\u003etoArray(); // returns [1, 2, 3, 4]\n```\n\nOccasionally, you'll want to specify the target collection to be pushed to. You may pass this as a third parameter.\n\n```php\n$collection = collect([1, 2, 3]);\n$collection-\u003efilter()-\u003efirstOrPush(fn($item) =\u003e $item === 4, 4, $collection);\n\n$collection-\u003etoArray(); // returns [1, 2, 3, 4]\n```\n\n### `fromPairs`\n\nTransform a collection into an associative array form collection item.\n\n```php\n$collection = collect([['a', 'b'], ['c', 'd'], ['e', 'f']])-\u003efromPairs();\n\n$collection-\u003etoArray(); // returns ['a' =\u003e 'b', 'c' =\u003e 'd', 'e' =\u003e 'f']\n```\n\n### `getCaseInsensitive`\n\nGet the value of a given key. \n\nIf the key is a string, we'll search for the key using a case-insensitive comparison.\n\n```php\n$collection = collect([\n    'foo' =\u003e 'bar',\n]);\n\n$collection-\u003egetCaseInsensitive('Foo'); // returns 'bar';\n```\n\n### `glob`\n\nReturns a collection of a `glob()` result.\n\n```php\nCollection::glob('config/*.php');\n```\n\n### `groupByModel`\n\nSimilar 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.\n\n```php\n$posts-\u003egroupByModel('category');\n\n// [\n//     [$categoryA, [/*...$posts*/]],\n//     [$categoryB, [/*...$posts*/]],\n// ];\n```\n\nFull signature: `groupByModel($callback, $preserveKeys, $modelKey, $itemsKey)`\n\n### `hasCaseInsensitive`\n\nDetermine if the collection contains a key with a given name.\n\nIf $key is a string, we'll search for the key using a case-insensitive comparison.\n\n```php\n$collection = collect([\n    'foo' =\u003e 'bar',\n]);\n\n$collection-\u003ehasCaseInsensitive('Foo'); // returns true;\n```\n\n### `head`\n\nRetrieves first item from the collection.\n\n```php\n$collection = collect([1,2,3]);\n\n$collection-\u003ehead(); // return 1\n\n$collection = collect([]);\n\n$collection-\u003ehead(); // return null\n```\n\n### `if`\n\nThe `if` macro can help  branch collection chains. This is the signature of this macro: \n\n```php\nif(mixed $if, mixed $then = null, mixed $else = null): mixed\n```\n\n`$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.\n\nWhen `$if` returns a truthy value, then `$then` will be returned, otherwise `$else` will be returned.\n\nHere are some examples:\n\n```php\ncollect()-\u003eif(true, then: true, else: false); // returns true\ncollect()-\u003eif(false, then: true, else: false); // returns false\n```\n\nWhen a closure is passed to `$if`, `$then` or `$else`, the entire collection will be passed as an argument to that closure.\n\n```php\n// the `then` closure will be executed\n// the first element of the returned collection now contains \"THIS IS THE VALUE\"\n$collection = collect(['this is a value'])\n    -\u003eif(\n        fn(Collection $collection) =\u003e $collection-\u003econtains('this is a value'),\n        then: fn(Collection $collection) =\u003e $collection-\u003emap(fn(string $item) =\u003e strtoupper($item)),\n        else: fn(Collection $collection) =\u003e $collection-\u003emap(fn(string $item) =\u003e Str::kebab($item))\n    );\n\n// the `else` closure will be executed\n// the first element of the returned collection now contains \"this-is-another-value\"\n$collection = collect(['this is another value'])\n    -\u003eif(\n        fn(Collection $collection) =\u003e $collection-\u003econtains('this is a value'),\n        then: fn(Collection $collection) =\u003e $collection-\u003emap(fn(string $item) =\u003e strtoupper($item)),\n        else: fn(Collection $collection) =\u003e $collection-\u003emap(fn(string $item) =\u003e Str::kebab($item))\n    );\n```\n\n### `ifAny`\n\nExecutes the passed callable if the collection isn't empty. The entire collection will be returned.\n\n```php\ncollect()-\u003eifAny(function(Collection $collection) { // empty collection so this won't get called\n   echo 'Hello';\n});\n\ncollect([1, 2, 3])-\u003eifAny(function(Collection $collection) { // non-empty collection so this will get called\n   echo 'Hello';\n});\n```\n\n### `ifEmpty`\n\nExecutes the passed callable if the collection is empty. The entire collection will be returned.\n\n```php\ncollect()-\u003eifEmpty(function(Collection $collection) { // empty collection so this will called\n   echo 'Hello';\n});\n\ncollect([1, 2, 3])-\u003eifEmpty(function(Collection $collection) { // non-empty collection so this won't get called\n   echo 'Hello';\n});\n```\n\n### `insertAfter`\n\nInserts an item after the first occurrence of a given item and returns the updated Collection instance.\nOptionally a key can be given.\n\n```php\ncollect(['zero', 'two', 'three'])-\u003einsertAfter('zero', 'one');\n// Collection contains ['zero', 'one', 'two', 'three']\n\ncollect(['zero' =\u003e 0, 'two' =\u003e 2, 'three' =\u003e 3]-\u003einsertAfter(0, 5, 'five');\n// Collection contains ['zero' =\u003e 0, 'five' =\u003e 5, 'two' =\u003e 2, 'three' =\u003e 3]\n```\n\n### `insertAfterKey`\n\nInserts an item after a given key and returns the updated Collection instance.\nOptionally a key for the new item can be given.\n\n```php\ncollect(['zero', 'two', 'three'])-\u003einsertAfterKey(0, 'one');\n// Collection contains ['zero', 'one', 'two', 'three']\n\ncollect(['zero' =\u003e 0, 'two' =\u003e 2, 'three' =\u003e 3]-\u003einsertAfterKey('zero', 5, 'five');\n// Collection contains ['zero' =\u003e 0, 'five' =\u003e 5, 'two' =\u003e 2, 'three' =\u003e 3]\n```\n\n### `insertAt`\n\nInserts an item at a given index and returns the updated Collection instance. Optionally a key can be given.\n\n```php\ncollect(['zero', 'two', 'three'])-\u003einsertAt(1, 'one');\n// Collection contains ['zero', 'one', 'two', 'three']\n\ncollect(['zero' =\u003e 0, 'two' =\u003e 2, 'three' =\u003e 3]-\u003einsertAt(1, 5, 'five');\n// Collection contains ['zero' =\u003e 0, 'five' =\u003e 5, 'two' =\u003e 2, 'three' =\u003e 3]\n```\n\n### `insertBefore`\n\nInserts an item before the first occurrence of a given item and returns the updated Collection instance.\nOptionally a key can be given.\n\n```php\ncollect(['zero', 'two', 'three'])-\u003einsertBefore('two', 'one');\n// Collection contains ['zero', 'one', 'two', 'three']\n\ncollect(['zero' =\u003e 0, 'two' =\u003e 2, 'three' =\u003e 3]-\u003einsertBefore(2, 5, 'five');\n// Collection contains ['zero' =\u003e 0, 'five' =\u003e 5, 'two' =\u003e 2, 'three' =\u003e 3]\n```\n\n### `insertBeforeKey`\n\nInserts an item before a given key and returns the updated Collection instance.\nOptionally a key for the new item can be given.\n\n```php\ncollect(['zero', 'two', 'three'])-\u003einsertBeforeKey(1, 'one');\n// Collection contains ['zero', 'one', 'two', 'three']\n\ncollect(['zero' =\u003e 0, 'two' =\u003e 2, 'three' =\u003e 3]-\u003einsertBeforeKey('two', 5, 'five');\n// Collection contains ['zero' =\u003e 0, 'five' =\u003e 5, 'two' =\u003e 2, 'three' =\u003e 3]\n```\n\n### `none`\n\nChecks 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.\n\n```php\ncollect(['foo'])-\u003enone('bar'); // returns true\ncollect(['foo'])-\u003enone('foo'); // returns false\n\ncollect([['name' =\u003e 'foo']])-\u003enone('name', 'bar'); // returns true\ncollect([['name' =\u003e 'foo']])-\u003enone('name', 'foo'); // returns false\n\ncollect(['name' =\u003e 'foo'])-\u003enone(function ($key, $value) {\n   return $key === 'name' \u0026\u0026 $value === 'bar';\n}); // returns true\n```\n\n### `paginate`\n\nCreate a `LengthAwarePaginator` instance for the items in the collection.\n\n```php\ncollect($posts)-\u003epaginate(5);\n```\n\nThis 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.\n\n```\npaginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])\n```\n\n### `path`\n\nReturns an item from the collection with multidimensional data using \"dot\" notation.\nWorks the same way as native Collection's `pull` method, but without removing an item from the collection.\n\n```php\n$collection = new Collection([\n    'foo' =\u003e [\n        'bar' =\u003e [\n            'baz' =\u003e 'value',\n        ]\n    ]\n]);\n\n$collection-\u003epath('foo.bar.baz') // 'value'\n```\n\n### `pluckMany`\n\nReturns a collection with only the specified keys.\n\n```php\n$collection = collect([\n    ['a' =\u003e 1, 'b' =\u003e 10, 'c' =\u003e 100],\n    ['a' =\u003e 2, 'b' =\u003e 20, 'c' =\u003e 200],\n]);\n\n$collection-\u003epluckMany(['a', 'b']);\n\n// returns\n// collect([\n//     ['a' =\u003e 1, 'b' =\u003e 10],\n//     ['a' =\u003e 2, 'b' =\u003e 20],\n// ]);\n```\n\n### `pluckManyValues`\n\nReturns a collection with only the specified keys' values.\n\n```php\n$collection = collect([\n    ['a' =\u003e 1, 'b' =\u003e 10, 'c' =\u003e 100],\n    ['a' =\u003e 2, 'b' =\u003e 20, 'c' =\u003e 200],\n]);\n\n$collection-\u003epluckMany(['a', 'b']);\n\n// returns\n// collect([\n//     [1, 10],\n//     [2, 20],\n// ]);\n```\n\n### `pluckToArray`\n\nReturns array of values of a given key.\n\n```php\n$collection = collect([\n    ['a' =\u003e 1, 'b' =\u003e 10],\n    ['a' =\u003e 2, 'b' =\u003e 20],\n    ['a' =\u003e 3, 'b' =\u003e 30]\n]);\n\n$collection-\u003epluckToArray('a'); // returns [1, 2, 3]\n```\n\n### `prioritize`\n\nMove elements to the start of the collection.\n\n```php\n$collection = collect([\n    ['id' =\u003e 1],\n    ['id' =\u003e 2],\n    ['id' =\u003e 3],\n]);\n\n$collection\n   -\u003eprioritize(function(array $item) {\n      return $item['id'] === 2;\n   })\n   -\u003epluck('id')\n   -\u003etoArray(); // returns [2, 1, 3]\n```\n\n### `recursive`\n\nConvert an array and its children to collection using recursion.\n\n```php\ncollect([\n  'item' =\u003e [\n     'children' =\u003e []\n  ]   \n])-\u003erecursive();\n\n// subsequent arrays are now collections\n```\n\nIn 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.\n\n```php\ncollect([\n  'item' =\u003e [\n     'children' =\u003e [\n        'one' =\u003e [1],\n        'two' =\u003e [2]\n     ]\n  ]   \n])-\u003erecursive(1); // Collection(['item' =\u003e Collection(['children' =\u003e ['one' =\u003e [1], 'two' =\u003e [2]]])])\n```\n\nThis can be useful when you know that at a certain depth it'll not be necessary or that it may break your code.\n\n```php\ncollect([\n  'item' =\u003e [\n     'children' =\u003e [\n        'one' =\u003e [1],\n        'two' =\u003e [2]\n     ]\n  ]   \n])\n  -\u003erecursive(1)\n  -\u003emap(function ($item) {\n    return $item-\u003emap(function ($children) {\n      return $children-\u003emapInto(Model::class);\n    });\n  }); // Collection(['item' =\u003e Collection(['children' =\u003e ['one' =\u003e Model(), 'two' =\u003e Model()]])])\n\n// If we do not pass a max depth we will get the error \"Argument #1 ($attributes) must be of type array\"\n```\n\n### `rotate`\n\nRotate the items in the collection with given offset\n\n```php\n$collection = collect([1, 2, 3, 4, 5, 6]);\n\n$rotate = $collection-\u003erotate(1);\n\n$rotate-\u003etoArray();\n\n// [2, 3, 4, 5, 6, 1]\n```\n\n### `sectionBy`\n\nSplits 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.\n\n```php\n$collection = collect([\n    ['name' =\u003e 'Lesson 1', 'module' =\u003e 'Basics'],\n    ['name' =\u003e 'Lesson 2', 'module' =\u003e 'Basics'],\n    ['name' =\u003e 'Lesson 3', 'module' =\u003e 'Advanced'],\n    ['name' =\u003e 'Lesson 4', 'module' =\u003e 'Advanced'],\n    ['name' =\u003e 'Lesson 5', 'module' =\u003e 'Basics'],\n]);\n\n$collection-\u003esectionBy('module');\n\n// [\n//     ['Basics', [\n//         ['name' =\u003e 'Lesson 1', 'module' =\u003e 'Basics'],\n//         ['name' =\u003e 'Lesson 2', 'module' =\u003e 'Basics'],\n//     ]],\n//     ['Advanced', [\n//         ['name' =\u003e 'Lesson 3', 'module' =\u003e 'Advanced'],\n//         ['name' =\u003e 'Lesson 4', 'module' =\u003e 'Advanced'],\n//     ]],\n//     ['Basics', [\n//         ['name' =\u003e 'Lesson 5', 'module' =\u003e 'Basics'],\n//     ]],\n// ];\n```\n\nFull signature: `sectionBy($callback, $preserveKeys, $sectionKey, $itemsKey)`\n\n### `simplePaginate`\n\nCreate a `Paginator` instance for the items in the collection.\n\n```php\ncollect($posts)-\u003esimplePaginate(5);\n```\n\nThis 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.\n\n```\nsimplePaginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])\n```\n\nFor a in-depth guide on pagination, check out [the Laravel docs](https://laravel.com/docs/5.4/pagination).\n\n### `sliceBefore`\n\nSlice 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.\n\n```php\ncollect([20, 51, 10, 50, 66])-\u003esliceBefore(function($item) {\n    return $item \u003e 50;\n}); // return collect([[20],[51, 10, 50], [66])\n```\n\n### `tail`\n\nExtract the tail from a collection. So everything except the first element. It's a shorthand for `slice(1)-\u003evalues()`, but nevertheless very handy. If the optional parameter `$preserveKeys` as `true` is passed, it will preserve the keys and fallback to `slice(1)`.\n\n```php\ncollect([1, 2, 3])-\u003etail(); // return collect([2, 3])\n```\n\n### `toPairs`\n\nTransform a collection into an array with pairs.\n\n```php\n$collection = collect(['a' =\u003e 'b', 'c' =\u003e 'd', 'e' =\u003e 'f'])-\u003etoPairs();\n\n$collection-\u003etoArray(); // returns ['a', 'b'], ['c', 'd'], ['e', 'f']\n```\n\n### `transpose`\n\nThe goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.\n\n```php\ncollect([\n    ['Jane', 'Bob', 'Mary'],\n    ['jane@example.com', 'bob@example.com', 'mary@example.com'],\n    ['Doctor', 'Plumber', 'Dentist'],\n])-\u003etranspose()-\u003etoArray();\n\n// [\n//     ['Jane', 'jane@example.com', 'Doctor'],\n//     ['Bob', 'bob@example.com', 'Plumber'],\n//     ['Mary', 'mary@example.com', 'Dentist'],\n// ]\n```\n\n### `try`\n\nIf any of the methods between `try` and `catch` throw an exception, then the exception can be handled in `catch`.\n\n```php\ncollect(['a', 'b', 'c', 1, 2, 3])\n    -\u003etry()\n    -\u003emap(fn ($letter) =\u003e strtoupper($letter))\n    -\u003eeach(function() {\n        throw new Exception('Explosions in the sky');\n    })\n    -\u003ecatch(function (Exception $exception) {\n        // handle exception here\n    })\n    -\u003emap(function() {\n        // further operations can be done, if the exception wasn't rethrow in the `catch`\n    });\n```\n\nWhile 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.\n\nYou 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.\n\n```php\n$collection = collect(['a', 'b', 'c', 1, 2, 3])\n    -\u003etry()\n    -\u003emap(function ($item) {\n        throw new Exception();\n    })\n    -\u003ecatch(function (Exception $exception, $collection) {\n        return collect(['d', 'e', 'f']);\n    })\n    -\u003emap(function ($item) {\n        return strtoupper($item);\n    });\n\n// ['D', 'E', 'F']\n```\n\n### `validate`\n\nReturns `true` if the given `$callback` returns true for every item. If `$callback` is a string or an array, regard it as a validation rule.\n\n```php\ncollect(['foo', 'foo'])-\u003evalidate(function ($item) {\n   return $item === 'foo';\n}); // returns true\n\n\ncollect(['sebastian@spatie.be', 'bla'])-\u003evalidate('email'); // returns false\ncollect(['sebastian@spatie.be', 'freek@spatie.be'])-\u003evalidate('email'); // returns true\n```\n\n### `weightedRandom`\n\nReturns 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.\n\n```php\n// pass the field name that should be used as a weight\n\n$randomItem = collect([\n    ['value' =\u003e 'a', 'weight' =\u003e 30],\n    ['value' =\u003e 'b', 'weight' =\u003e 20],\n    ['value' =\u003e 'c', 'weight' =\u003e 10],\n])-\u003eweightedRandom('weight');\n```\n\nAlternatively, you can pass a callable to get the weight.\n\n```php\n$randomItem = collect([\n    ['value' =\u003e 'a', 'weight' =\u003e 30],\n    ['value' =\u003e 'b', 'weight' =\u003e 20],\n    ['value' =\u003e 'c', 'weight' =\u003e 10],\n])-\u003eweightedRandom(function(array $item) {\n   return $item['weight'];\n});\n```\n\n\n\n### `withSize`\n\nCreate a new collection with the specified amount of items.\n\n```php\nCollection::withSize(1)-\u003etoArray(); // return [1];\nCollection::withSize(5)-\u003etoArray(); // return [1,2,3,4,5];\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Testing\n\n``` bash\n$ composer test\n```\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Credits\n\n- [Freek Van der Herten](https://github.com/freekmurze)\n- [Sebastian De Deyne](https://github.com/sebastiandedeyne)\n- [All Contributors](../../contributors)\n\n## About Spatie\nSpatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-collection-macros","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Flaravel-collection-macros","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-collection-macros/lists"}