### Installing Laravel Collection Macros via Composer Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This command installs the `spatie/laravel-collection-macros` package using Composer. It adds the package as a dependency to your Laravel project, allowing its collection macros to be automatically registered and available for use. ```bash composer require spatie/laravel-collection-macros ``` -------------------------------- ### Getting First Item or Throwing Exception from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the first item from the collection. If the collection is empty or no item is found, it throws a `Spatie\CollectionMacros\Exceptions\CollectionItemNotFound` exception, ensuring that an item is always present or an error is explicitly handled. ```PHP $collection = collect([1, 2, 3, 4, 5, 6])->firstOrFail(); $collection->toArray(); // returns [1] collect([])->firstOrFail(); // throws Spatie\CollectionMacros\Exceptions\CollectionItemNotFound ``` -------------------------------- ### Creating New Collection with Specific Size (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This snippet demonstrates the `withSize` static method, which creates a new collection containing a specified number of sequential integer items, starting from 1. It's useful for quickly generating collections of a predetermined length. ```php Collection::withSize(1)->toArray(); // return [1]; Collection::withSize(5)->toArray(); // return [1,2,3,4,5]; ``` -------------------------------- ### Using `after` Macro with Fallback in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This example demonstrates using the `after` macro with an optional second parameter as a fallback. If the current item is the last in the collection, or if no next item is found, the specified fallback value (in this case, the first item) will be returned instead of `null`. ```php $collection = collect([1,2,3]); $currentItem = 3; $collection->after($currentItem, $collection->first()); // return 1; ``` -------------------------------- ### Slicing Collection Before Callback in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `sliceBefore` macro extracts a slice of values from a collection, starting from the beginning and ending just before the point where a provided callback function returns true. An optional boolean parameter allows preserving the original keys of the sliced items. ```PHP collect([20, 51, 10, 50, 66])->sliceBefore(function($item) { return $item > 50; }); // return collect([[20],[51, 10, 50], [66]) ``` -------------------------------- ### Manipulating Collection in try/catch Block (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This example shows how to access and manipulate the collection within the `catch` callback. By returning a new collection from the `catch` handler, subsequent operations will be performed on the returned collection instead of the original one, effectively transforming the collection upon exception. ```php $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'] ``` -------------------------------- ### Getting Next Item with `after` Macro in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `after` macro retrieves the item immediately following a given item in the collection. It can accept either a direct value or a callback function to find the current item. If no next item is found, it returns `null`. ```php $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; ``` -------------------------------- ### Selecting Weighted Random Item by Field Name (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This example demonstrates using `weightedRandom` to select an item from a collection based on a specified weight field. The item with the highest weight has the greatest chance of being selected, providing a probabilistic selection mechanism. ```php // 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'); ``` -------------------------------- ### Getting Case-Insensitive Key Value in Laravel Collection (getCaseInsensitive) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro retrieves the value associated with a given key from the collection. If the key is a string, the search is performed using a case-insensitive comparison, allowing retrieval regardless of the key's casing in the collection. ```php $collection = collect([ 'foo' => 'bar', ]); $collection->getCaseInsensitive('Foo'); // returns 'bar'; ``` -------------------------------- ### Getting Previous Item with Fallback in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item immediately preceding the given `$currentItem`, allowing a second parameter to be passed as a fallback value if no previous item is found. This ensures a default value is returned instead of `null`. ```PHP $collection = collect([1,2,3]); $currentItem = 1; $collection->before($currentItem, $collection->last()); // return 3; ``` -------------------------------- ### Retrieving Eighth Item from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item located at the eighth index (index 7) of a Laravel Collection. It offers a straightforward way to get elements by their ordinal position. ```PHP $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->eighth(); // 8 ``` -------------------------------- ### Getting Previous Item in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item immediately preceding the given `$currentItem` in the collection. It can accept either a direct value or a callback function to determine the current item, returning `null` if no previous item is found. ```PHP $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; ``` -------------------------------- ### Getting Consecutive Neighbors in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method generates a new collection containing arrays of consecutive elements from the original collection, based on a specified chunk size. It's useful for processing sliding windows of data, with an option to preserve original keys. ```PHP collect([1, 2, 3, 4])->eachCons(2); // return collect([[1, 2], [2, 3], [3, 4]]) ``` -------------------------------- ### Running Composer Tests (Bash) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This command snippet shows how to execute the test suite for the project using Composer. It's a standard practice in PHP projects to run tests via `composer test` to ensure code quality and functionality. ```bash $ composer test ``` -------------------------------- ### Retrieving the First Item of a Laravel Collection (head) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro retrieves the very first item from the collection. If the collection is empty, it returns `null`. ```php $collection = collect([1,2,3]); $collection->head(); // return 1 $collection = collect([]); $collection->head(); // return null ``` -------------------------------- ### Handling Exceptions with try/catch in Laravel Collections (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This snippet demonstrates how to use the `try` and `catch` macros on a Laravel Collection to handle exceptions. If an exception is thrown within the `try` block, the `catch` callback is executed, allowing for error handling without rethrowing, and further operations can proceed on the original collection state. ```php 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` }); ``` -------------------------------- ### Globbing Files into a Laravel Collection (glob) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro returns a new collection containing the results of a `glob()` operation, effectively collecting file paths matching a specified pattern. ```php Collection::glob('config/*.php'); ``` -------------------------------- ### Simple Pagination for Collections in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `simplePaginate` macro generates a `Paginator` instance for the items within a collection. It allows for easy pagination of collection contents, specifying the number of items per page and other pagination options. ```PHP collect($posts)->simplePaginate(5); ``` -------------------------------- ### Collecting Item by Key with Fallback from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves an item at a specified key and collects it, similar to `collectBy`. It also accepts a second parameter as a fallback value, which will be collected and returned if the specified key does not exist in the original collection. ```PHP $collection = collect([ 'foo' => [1, 2, 3], 'bar' => [4, 5, 6], ]); $collection->collectBy('baz', ['Nope']); // Collection(['Nope']) ``` -------------------------------- ### Transforming Collection to Associative Array (fromPairs) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro transforms a collection of key-value pairs (e.g., `[['a', 'b'], ['c', 'd']]`) into an associative array where the first element of each inner array becomes the key and the second becomes the value. ```php $collection = collect([['a', 'b'], ['c', 'd'], ['e', 'f']])->fromPairs(); $collection->toArray(); // returns ['a' => 'b', 'c' => 'd', 'e' => 'f'] ``` -------------------------------- ### Paginating Laravel Collection Items (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Creates a `LengthAwarePaginator` instance for the items within the collection, enabling easy pagination of collection data. The method accepts parameters for items per page, page name, current page, total items, and additional options, similar to Laravel's native pagination. ```PHP collect($posts)->paginate(5); ``` -------------------------------- ### Extracting Keys as Array from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method extracts specified keys from a collection, returning an array of their values. Unlike `only`, it fills non-existent keys with `null` and is particularly useful with PHP 7.1+ `list()` syntax for destructuring. ```PHP [$name, $role] = collect($user)->extract('name', 'role.name'); ``` -------------------------------- ### Executing Callable if Laravel Collection is Empty (ifEmpty) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro executes a provided callable function only if the collection is empty. The entire collection instance is passed to the callable, and the collection itself is returned, allowing for continued chaining. ```php 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'; }); ``` -------------------------------- ### Executing Callable if Laravel Collection is Not Empty (ifAny) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro executes a provided callable function only if the collection is not empty. The entire collection instance is passed to the callable, and the collection itself is returned, allowing for continued chaining. ```php 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'; }); ``` -------------------------------- ### Prioritizing Elements in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Moves elements that satisfy a given truth test to the beginning of the collection, effectively prioritizing them. The method accepts a callback function to determine which items should be moved. It returns the modified collection instance. ```PHP $collection = collect([ ['id' => 1], ['id' => 2], ['id' => 3], ]); $collection ->prioritize(function(array $item) { return $item['id'] === 2; }) ->pluck('id') ->toArray(); // returns [2, 1, 3] ``` -------------------------------- ### Retrieving or Pushing First Item in Laravel Collection (firstOrPush) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro retrieves the first item from a collection based on a callable condition. If no item matches, it pushes a specified value (or the result of a callable) into the collection. It's particularly useful for caching scenarios where you want to store a computationally expensive value if it doesn't already exist. An optional third parameter allows specifying a different target collection for the push operation. ```php $collection = collect([1, 2, 3])->firstOrPush(fn($item) => $item === 4, 4); $collection->toArray(); // returns [1, 2, 3, 4] ``` ```php $collection = collect([1, 2, 3]); $collection->filter()->firstOrPush(fn($item) => $item === 4, 4, $collection); $collection->toArray(); // returns [1, 2, 3, 4] ``` -------------------------------- ### Transforming Collection to Pairs in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `toPairs` macro converts a collection into an array where each element is a two-item array representing a key-value pair from the original collection. This is useful for restructuring data into a list of explicit pairs. ```PHP $collection = collect(['a' => 'b', 'c' => 'd', 'e' => 'f'])->toPairs(); $collection->toArray(); // returns ['a', 'b'], ['c', 'd'], ['e', 'f'] ``` -------------------------------- ### Retrieving Item by Index with `at` Macro in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `at` macro allows retrieving an item from the collection at a specific zero-based index. It supports both positive indices (from the beginning) and negative indices (from the end of the collection), similar to array indexing. ```php $data = new Collection([1, 2, 3]); $data->at(0); // 1 $data->at(1); // 2 $data->at(-1); // 3 ``` -------------------------------- ### Collecting Item by Key from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves an item at a specified key from the collection and wraps it in a new Laravel Collection instance. It's useful for accessing nested array-like structures and immediately converting them into a collection. ```PHP $collection = collect([ 'foo' => [1, 2, 3], 'bar' => [4, 5, 6], ]); $collection->collectBy('foo'); // Collection([1, 2, 3]) ``` -------------------------------- ### Selecting Weighted Random Item with Callable (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This snippet shows an alternative usage of `weightedRandom` where a callable function is provided to determine the weight of each item. This allows for more complex logic to calculate weights dynamically, rather than relying on a fixed field name. ```php $randomItem = collect([ ['value' => 'a', 'weight' => 30], ['value' => 'b', 'weight' => 20], ['value' => 'c', 'weight' => 10] ])->weightedRandom(function(array $item) { return $item['weight']; }); ``` -------------------------------- ### Conditional Branching in Laravel Collection Chains (if) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `if` macro enables conditional branching within collection chains. It accepts an `$if` condition, a `$then` value/closure, and an optional `$else` value/closure. If `$if` evaluates to truthy, `$then` is returned; otherwise, `$else` is returned. Closures passed to any parameter will be executed with the entire collection as an argument. ```php collect()->if(true, then: true, else: false); // returns true collect()->if(false, then: true, else: false); // returns false ``` ```php // 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)) ); ``` -------------------------------- ### Inserting Item Before Specific Key in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Inserts an item before a given key in the collection, returning the updated Collection instance. This method is useful for precise key-based insertions. An optional key can be provided for the new item to be inserted. ```PHP 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] ``` -------------------------------- ### Retrieving Second Item with `second` Macro in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `second` macro is a convenience method that retrieves the item at the second position (index 1) of the collection. It provides a more readable way to access specific indexed elements without explicitly using `at(1)`. ```php $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->second(); // 2 ``` -------------------------------- ### Extracting Collection Tail in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `tail` macro extracts all elements from a collection except the first one, effectively returning the 'tail' of the collection. It serves as a convenient shorthand for `slice(1)->values()`, and can optionally preserve original keys if specified. ```PHP collect([1, 2, 3])->tail(); // return collect([2, 3]) ``` -------------------------------- ### Plucking Multiple Key Values from Laravel Collection Items (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Returns a new collection where each item contains only the values associated with the specified keys from the original collection's items. This differs from `pluckMany` by returning only the values in a flat array for each sub-item, rather than key-value pairs. ```PHP $collection = collect([ ['a' => 1, 'b' => 10, 'c' => 100], ['a' => 2, 'b' => 20, 'c' => 200], ]); $collection->pluckMany(['a', 'b']); ``` -------------------------------- ### Checking for Case-Insensitive Key Existence in Laravel Collection (hasCaseInsensitive) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This macro determines if the collection contains a key with a given name. If the key is a string, the check is performed using a case-insensitive comparison, making it robust against casing differences. ```php $collection = collect([ 'foo' => 'bar', ]); $collection->hasCaseInsensitive('Foo'); // returns true; ``` -------------------------------- ### Plucking Key Values to Array from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Returns a plain PHP array containing the values of a specified key from all items in the collection. This is a convenient way to extract a single column of data from a collection into a simple list. ```PHP $collection = collect([ ['a' => 1, 'b' => 10], ['a' => 2, 'b' => 20], ['a' => 3, 'b' => 30] ]); $collection->pluckToArray('a'); // returns [1, 2, 3] ``` -------------------------------- ### Checking for All Values Existence in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method verifies if all of the given values are present in the collection. It returns `true` only if every specified value is found, and `false` otherwise. An empty array of values will return `true`. ```PHP $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 ``` -------------------------------- ### Checking for Any Value Existence in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method determines if at least one of the provided values exists within the collection. It returns `true` if any match is found, and `false` otherwise, including for an empty array of values. ```PHP $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 ``` -------------------------------- ### Inserting Item Before Occurrence in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Inserts an item before the first occurrence of a specified item in the collection, returning the modified Collection instance. This macro facilitates inserting new elements relative to existing values. An optional key can be provided for the new item. ```PHP 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] ``` -------------------------------- ### Inserting Item After Occurrence in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Inserts an item after the first occurrence of a given item in the collection. This macro returns the updated Collection instance. An optional key can be provided for the new item, allowing for associative insertions. ```PHP 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] ``` -------------------------------- ### Inserting Item After Specific Key in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Inserts an item after a specified key within the collection, returning the modified Collection instance. This method allows for precise placement of new elements based on existing keys. An optional key can be given for the new item. ```PHP 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] ``` -------------------------------- ### Filtering and Mapping Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method combines the functionality of `map` and `filter`, allowing a collection to be transformed and simultaneously removing any falsy values returned by the callback. It's an efficient way to process and clean data in one operation. ```PHP $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] ``` -------------------------------- ### Chunking Laravel Collection by Callback Condition (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method divides a collection into smaller chunks based on a callback function, grouping consecutive elements as long as the callback returns true. An optional `$preserveKeys` parameter can be set to `true` to maintain original keys in the resulting chunks. ```PHP collect(['A', 'A', 'B', 'A'])->chunkBy(function($item) { return $item == 'A'; }); // return Collection([['A', 'A'],['B'], ['A']]) ``` -------------------------------- ### Grouping Laravel Collection by Eloquent Model (groupByModel) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Similar to the standard `groupBy` method, this macro groups the collection by an Eloquent model. Because the grouping key is an object (the model instance), the results are structured as separate arrays, each containing the model and its associated collection items. The full signature allows for custom callbacks, key preservation, and specifying model/item keys. ```php $posts->groupByModel('category'); // [ // [$categoryA, [/*...$posts*/]], // [$categoryB, [/*...$posts*/]], // ]; ``` -------------------------------- ### Transposing Multidimensional Collections in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `transpose` macro reorients a multidimensional collection by swapping its rows and columns. This operation is useful for changing the perspective of tabular data, turning what were rows into columns and vice-versa. ```PHP 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'], // ] ``` -------------------------------- ### Validating Collection Items with Callback and Rules (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This snippet illustrates the `validate` macro, which checks if all items in a collection satisfy a given condition. It supports both a callable function for custom validation logic and a string/array for using Laravel's built-in validation rules (e.g., 'email'). It returns `true` if all items pass validation, `false` otherwise. ```php 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 ``` -------------------------------- ### Retrieving Third Item with `third` Macro in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `third` macro is a convenience method that retrieves the item at the third position (index 2) of the collection. It simplifies accessing specific indexed elements, offering improved code readability over `at(2)`. ```php $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->third(); // 3 ``` -------------------------------- ### Retrieving Nth Item from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item at the specified 'nth' position (1-based index) from a Laravel Collection. It provides a flexible way to access elements by their ordinal position, unlike the fixed `sixth`, `seventh`, etc., methods. ```PHP $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); $data->getNth(11); // 11 ``` -------------------------------- ### Accessing Nested Data by Dot Notation in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Retrieves an item from a collection containing multidimensional data using 'dot' notation. Unlike the native `pull` method, `path` fetches the item without removing it from the collection, preserving the original data structure. ```PHP $collection = new Collection([ 'foo' => [ 'bar' => [ 'baz' => 'value', ] ] ]); $collection->path('foo.bar.baz') // 'value' ``` -------------------------------- ### Grouping Collection Items by Section in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `sectionBy` macro divides a collection into distinct sections based on a given key. Unlike `groupBy`, it maintains the original order of items and reuses existing keys for consecutive sections, providing a more ordered and segmented grouping. ```PHP $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'], // ]], // ]; ``` -------------------------------- ### Converting Arrays Recursively to Collections in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `recursive` macro converts an array and its nested children into collections. It can be used without arguments to convert all subsequent arrays or with a numeric argument to limit the conversion depth, preventing potential errors or unnecessary conversions at deeper levels. ```PHP collect([ 'item' => [ 'children' => [] ] ])->recursive(); // subsequent arrays are now collections ``` ```PHP collect([ 'item' => [ 'children' => [ 'one' => [1], 'two' => [2] ] ] ])->recursive(1); // Collection(['item' => Collection(['children' => ['one' => [1], 'two' => [2]]])]) ``` ```PHP 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" ``` -------------------------------- ### Retrieving Fifth Item with `fifth` Macro in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `fifth` macro is a convenience method that retrieves the item at the fifth position (index 4) of the collection. It offers a more semantic and readable way to access specific indexed elements compared to `at(4)`. ```php $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->fifth(); // 5 ``` -------------------------------- ### Checking for Absence of Items in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Checks if a collection does not contain any occurrences of a given item, a specific key-value pair, or elements that pass a truth test. It functions as the inverse of the native `contains` method, returning `true` if no match is found, and `false` otherwise. ```PHP 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 ``` -------------------------------- ### Inserting Item at Specific Index in Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Inserts an item at a specific numerical index within the collection, returning the updated Collection instance. This is useful for precise positional insertions. An optional key can be provided for the new item, allowing for associative insertions at a given index. ```PHP 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] ``` -------------------------------- ### Plucking Multiple Keys from Laravel Collection Items (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md Returns a new collection containing only the specified keys from each item in the original collection. This is useful for filtering down the attributes of nested objects or arrays within a collection, preserving the structure of the sub-arrays/objects. ```PHP $collection = collect([ ['a' => 1, 'b' => 10, 'c' => 100], ['a' => 2, 'b' => 20, 'c' => 200], ]); $collection->pluckMany(['a', 'b']); ``` -------------------------------- ### Retrieving Seventh Item from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item located at the seventh index (index 6) of a Laravel Collection. It simplifies direct access to elements based on their ordinal position. ```PHP $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->seventh(); // 7 ``` -------------------------------- ### Retrieving Fourth Item with `fourth` Macro in Laravel Collections Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `fourth` macro is a convenience method that retrieves the item at the fourth position (index 3) of the collection. It enhances code readability for accessing specific indexed elements, providing a clear alternative to `at(3)`. ```php $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->fourth(); // 4 ``` -------------------------------- ### Rotating Collection Items in PHP Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md The `rotate` macro shifts the items within a collection by a specified offset. This operation effectively moves elements from the beginning to the end of the collection, or vice-versa, depending on the offset value. ```PHP $collection = collect([1, 2, 3, 4, 5, 6]); $rotate = $collection->rotate(1); $rotate->toArray(); // [2, 3, 4, 5, 6, 1] ``` -------------------------------- ### Retrieving Tenth Item from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item located at the tenth index (index 9) of a Laravel Collection. It simplifies accessing elements based on their ordinal position. ```PHP $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->tenth(); // 10 ``` -------------------------------- ### Retrieving Sixth Item from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item located at the sixth index (index 5) of a Laravel Collection. It provides a convenient way to access specific elements by their ordinal position. ```PHP $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->sixth(); // 6 ``` -------------------------------- ### Retrieving Ninth Item from Laravel Collection (PHP) Source: https://github.com/spatie/laravel-collection-macros/blob/main/README.md This method retrieves the item located at the ninth index (index 8) of a Laravel Collection. It provides a direct approach to access elements by their ordinal position. ```PHP $data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $data->ninth(); // 9 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.