Debug School

rakesh kumar
rakesh kumar

Posted on

Explain Collections Methods Part-III

  1. lazy
  2. macro
  3. make
  4. map
  5. mapInto
  6. mapSpread
  7. mapToGroups
  8. mapWithKeys
  9. max
  10. median
  11. merge
  12. mergeRecursive
  13. min
  14. mode
  15. nth
  16. only
  17. pad
  18. partition
  19. pipe
  20. pipeInto
  21. pipeThrough
  22. pluck
  23. pop
  24. prepend
  25. pull
  26. push
  27. put
  28. random
  29. range
  30. reduce
  31. reduceSpread
  32. reject
  33. replace
  34. replaceRecursive
  35. reverse
  36. search
  37. shift
  38. shuffle
  39. skip
  40. skipUntil
  41. skipWhile
  42. slice
  43. sliding
  44. sole
  45. some
  46. sort
  47. sortBy
  48. sortByDesc
  49. sortDesc
  50. sortKeys
  51. sortKeysDesc
  52. sortKeysUsing
  53. splice
  54. split
  55. splitIn
  56. sum
  57. take
  58. takeUntil
  59. takeWhile
  60. tap
  61. times
  62. toArray
  63. toJson
  64. transform
  65. $filtered = $collection->pad(-5, 0);
  66. $filtered->all();

lazy()
The lazy method returns a new LazyCollection instance from the underlying array of items:

$lazyCollection = collect([1, 2, 3, 4])->lazy();

get_class($lazyCollection);

// Illuminate\Support\LazyCollection

$lazyCollection->all();

// [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

This is especially useful when you need to perform transformations on a huge Collection that contains many items:

$count = $hugeCollection
    ->lazy()
    ->where('country', 'FR')
    ->where('balance', '>', '100')
    ->count();
Enter fullscreen mode Exit fullscreen mode

By converting the collection to a LazyCollection, we avoid having to allocate a ton of additional memory. Though the original collection still keeps its values in memory, the subsequent filters will not. Therefore, virtually no additional memory will be allocated when filtering the collection's results.

macro()
The static macro method allows you to add methods to the Collection class at run time. Refer to the documentation on extending collections for more information.

make()
The static make method creates a new collection instance. See the Creating Collections section.

map()
The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

$collection = collect([1, 2, 3, 4, 5]);

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the transform method.

mapInto()
The mapInto() method iterates over the collection, creating a new instance of the given class by passing the value into the constructor:

class Currency
{
    /**
     * Create a new currency instance.
     *
     * @param  string  $code
     * @return void
     */
    function __construct(string $code)
    {
        $this->code = $code;
    }
}

$collection = collect(['USD', 'EUR', 'GBP']);

$currencies = $collection->mapInto(Currency::class);

$currencies->all();

// [Currency('USD'), Currency('EUR'), Currency('GBP')]
Enter fullscreen mode Exit fullscreen mode

mapSpread()
The mapSpread method iterates over the collection's items, passing each nested item value into the given closure. The closure is free to modify the item and return it, thus forming a new collection of modified items:

$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunks = $collection->chunk(2);

$sequence = $chunks->mapSpread(function ($even, $odd) {
    return $even + $odd;
});

$sequence->all();

// [1, 5, 9, 13, 17]
Enter fullscreen mode Exit fullscreen mode

mapToGroups()
The mapToGroups method groups the collection's items by the given closure. The closure should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:

$collection = collect([
    [
        'name' => 'John Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Jane Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Johnny Doe',
        'department' => 'Marketing',
    ]
]);

$grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
});

$grouped->all();

/*
    [
        'Sales' => ['John Doe', 'Jane Doe'],
        'Marketing' => ['Johnny Doe'],
    ]
*/

$grouped->get('Sales')->all();

// ['John Doe', 'Jane Doe']
Enter fullscreen mode Exit fullscreen mode

mapWithKeys()
The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com',
    ]
]);

$keyed = $collection->mapWithKeys(function ($item, $key) {
    return [$item['email'] => $item['name']];
});

$keyed->all();

/*
    [
        'john@example.com' => 'John',
        'jane@example.com' => 'Jane',
    ]
*/
Enter fullscreen mode Exit fullscreen mode

max()
The max method returns the maximum value of a given key:

$max = collect([
    ['foo' => 10],
    ['foo' => 20]
])->max('foo');

// 20

$max = collect([1, 2, 3, 4, 5])->max();

// 5
Enter fullscreen mode Exit fullscreen mode

median()
The median method returns the median value of a given key:

$median = collect([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
])->median('foo');

// 15

$median = collect([1, 1, 2, 4])->median();

// 1.5
Enter fullscreen mode Exit fullscreen mode

merge()
The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:

$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->merge(['price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => 1, 'price' => 200, 'discount' => false]
Enter fullscreen mode Exit fullscreen mode

If the given items's keys are numeric, the values will be appended to the end of the collection:

$collection = collect(['Desk', 'Chair']);

$merged = $collection->merge(['Bookcase', 'Door']);

$merged->all();

// ['Desk', 'Chair', 'Bookcase', 'Door']
Enter fullscreen mode Exit fullscreen mode

mergeRecursive()
The mergeRecursive method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively:

$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->mergeRecursive([
    'product_id' => 2,
    'price' => 200,
    'discount' => false
]);

$merged->all();

// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]
Enter fullscreen mode Exit fullscreen mode

min()
The min method returns the minimum value of a given key:

$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');

// 10

$min = collect([1, 2, 3, 4, 5])->min();

// 1
Enter fullscreen mode Exit fullscreen mode

mode()
The mode method returns the mode value of a given key:

$mode = collect([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
])->mode('foo');

// [10]

$mode = collect([1, 1, 2, 4])->mode();

// [1]

$mode = collect([1, 1, 2, 2])->mode();

// [1, 2]
Enter fullscreen mode Exit fullscreen mode

nth()
The nth method creates a new collection consisting of every n-th element:

$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

$collection->nth(4);

// ['a', 'e']
Enter fullscreen mode Exit fullscreen mode

You may optionally pass a starting offset as the second argument:

$collection->nth(4, 1);

// ['b', 'f']
Enter fullscreen mode Exit fullscreen mode

only()
The only method returns the items in the collection with the specified keys:

$collection = collect([
    'product_id' => 1,
    'name' => 'Desk',
    'price' => 100,
    'discount' => false
]);
Enter fullscreen mode Exit fullscreen mode
$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']
Enter fullscreen mode Exit fullscreen mode

For the inverse of only, see the except method.

This method's behavior is modified when using Eloquent Collections.

pad()
The pad method will fill the array with the given value until the array reaches the specified size. This method behaves like the array_pad PHP function.

To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array:

$collection = collect(['A', 'B', 'C']);

$filtered = $collection->pad(5, 0);

$filtered->all();

// ['A', 'B', 'C', 0, 0]

$filtered = $collection->pad(-5, 0);

$filtered->all();

// [0, 0, 'A', 'B', 'C']
Enter fullscreen mode Exit fullscreen mode

partition()
The partition method may be combined with PHP array destructuring to separate elements that pass a given truth test from those that do not:

$collection = collect([1, 2, 3, 4, 5, 6]);

[$underThree, $equalOrAboveThree] = $collection->partition(function ($i) {
    return $i < 3;
});

$underThree->all();

// [1, 2]

$equalOrAboveThree->all();

// [3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

pipe()
The pipe method passes the collection to the given closure and returns the result of the executed closure:

$collection = collect([1, 2, 3]);

$piped = $collection->pipe(function ($collection) {
    return $collection->sum();
});

// 6
Enter fullscreen mode Exit fullscreen mode

pipeInto()
The pipeInto method creates a new instance of the given class and passes the collection into the constructor:

class ResourceCollection
{
    /**
     * The Collection instance.
     */
    public $collection;

    /**
     * Create a new ResourceCollection instance.
     *
     * @param  Collection  $collection
     * @return void
     */
    public function __construct(Collection $collection)
    {
        $this->collection = $collection;
    }
}

Enter fullscreen mode Exit fullscreen mode
$collection = collect([1, 2, 3]);

$resource = $collection->pipeInto(ResourceCollection::class);

$resource->collection->all();

// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

pipeThrough()
The pipeThrough method passes the collection to the given array of closures and returns the result of the executed closures:

$collection = collect([1, 2, 3]);

$result = $collection->pipeThrough([
    function ($collection) {
        return $collection->merge([4, 5]);
    },
    function ($collection) {
        return $collection->sum();
    },
]);

// 15
Enter fullscreen mode Exit fullscreen mode

pluck()
The pluck method retrieves all of the values for a given key:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

// ['Desk', 'Chair']
Enter fullscreen mode Exit fullscreen mode

You may also specify how you wish the resulting collection to be keyed:

$plucked = $collection->pluck('name', 'product_id');

$plucked->all();

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Enter fullscreen mode Exit fullscreen mode

The pluck method also supports retrieving nested values using "dot" notation:

$collection = collect([
    [
        'name' => 'Laracon',
        'speakers' => [
            'first_day' => ['Rosa', 'Judith'],
        ],
    ],
    [
        'name' => 'VueConf',
        'speakers' => [
            'first_day' => ['Abigail', 'Joey'],
        ],
    ],
]);
Enter fullscreen mode Exit fullscreen mode
$plucked = $collection->pluck('speakers.first_day');

$plucked->all();

// [['Rosa', 'Judith'], ['Abigail', 'Joey']]
Enter fullscreen mode Exit fullscreen mode

If duplicate keys exist, the last matching element will be inserted into the plucked collection:

$collection = collect([
    ['brand' => 'Tesla',  'color' => 'red'],
    ['brand' => 'Pagani', 'color' => 'white'],
    ['brand' => 'Tesla',  'color' => 'black'],
    ['brand' => 'Pagani', 'color' => 'orange'],
]);

$plucked = $collection->pluck('color', 'brand');

$plucked->all();

// ['Tesla' => 'black', 'Pagani' => 'orange']
Enter fullscreen mode Exit fullscreen mode

pop()
The pop method removes and returns the last item from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

You may pass an integer to the pop method to remove and return multiple items from the end of a collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->pop(3);

// collect([5, 4, 3])

$collection->all();

// [1, 2]
Enter fullscreen mode Exit fullscreen mode

prepend()
The prepend method adds an item to the beginning of the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

You may also pass a second argument to specify the key of the prepended item:

$collection = collect(['one' => 1, 'two' => 2]);

$collection->prepend(0, 'zero');

$collection->all();

// ['zero' => 0, 'one' => 1, 'two' => 2]
Enter fullscreen mode Exit fullscreen mode

pull()
The pull method removes and returns an item from the collection by its key:

$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);

$collection->pull('name');

// 'Desk'

$collection->all();

// ['product_id' => 'prod-100']
Enter fullscreen mode Exit fullscreen mode

push()
The push method appends an item to the end of the collection:

$collection = collect([1, 2, 3, 4]);

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

put()
The put method sets the given key and value in the collection:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
Enter fullscreen mode Exit fullscreen mode

random()
The random method returns a random item from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->random();

// 4 - (retrieved randomly)
Enter fullscreen mode Exit fullscreen mode

You may pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:

$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (retrieved randomly)
Enter fullscreen mode Exit fullscreen mode

If the collection instance has fewer items than requested, the random method will throw an InvalidArgumentException.

The random method also accepts a closure, which will receive the current collection instance:

$random = $collection->random(fn ($items) => min(10, count($items)));

$random->all();

// [1, 2, 3, 4, 5] - (retrieved randomly)
Enter fullscreen mode Exit fullscreen mode

range()
The range method returns a collection containing integers between the specified range:

$collection = collect()->range(3, 6);

$collection->all();

// [3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

reduce()
The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

$collection = collect([1, 2, 3]);

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});
Enter fullscreen mode Exit fullscreen mode

// 6

The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

$collection->reduce(function ($carry, $item) {
    return $carry + $item;
}, 4);
Enter fullscreen mode Exit fullscreen mode

// 10

The reduce method also passes array keys in associative collections to the given callback:

$collection = collect([
    'usd' => 1400,
    'gbp' => 1200,
    'eur' => 1000,
]);

$ratio = [
    'usd' => 1,
    'gbp' => 1.37,
    'eur' => 1.22,
];

$collection->reduce(function ($carry, $value, $key) use ($ratio) {
    return $carry + ($value * $ratio[$key]);
});
Enter fullscreen mode Exit fullscreen mode

// 4264

reduceSpread()
The reduceSpread method reduces the collection to an array of values, passing the results of each iteration into the subsequent iteration. This method is similar to the reduce method; however, it can accept multiple initial values:

[$creditsRemaining, $batch] = Image::where('status', 'unprocessed')
    ->get()
    ->reduceSpread(function ($creditsRemaining, $batch, $image) {
        if ($creditsRemaining >= $image->creditsRequired()) {
            $batch->push($image);

            $creditsRemaining -= $image->creditsRequired();
        }

        return [$creditsRemaining, $batch];
    }, $creditsAvailable, collect());
Enter fullscreen mode Exit fullscreen mode

reject()
The reject method filters the collection using the given closure. The closure should return true if the item should be removed from the resulting collection:

$collection = collect([1, 2, 3, 4]);

$filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
});

$filtered->all();
Enter fullscreen mode Exit fullscreen mode

// [1, 2]

For the inverse of the reject method, see the filter method.

replace()
The replace method behaves similarly to merge; however, in addition to overwriting matching items that have string keys, the replace method will also overwrite items in the collection that have matching numeric keys:

$collection = collect(['Taylor', 'Abigail', 'James']);

$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);

$replaced->all();

// ['Taylor', 'Victoria', 'James', 'Finn']
Enter fullscreen mode Exit fullscreen mode

replaceRecursive()
This method works like replace, but it will recur into arrays and apply the same replacement process to the inner values:

$collection = collect([
    'Taylor',
    'Abigail',
    [
        'James',
        'Victoria',
        'Finn'
    ]
]);

$replaced = $collection->replaceRecursive([
    'Charlie',
    2 => [1 => 'King']
]);

$replaced->all();
Enter fullscreen mode Exit fullscreen mode

// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]

reverse()
The reverse method reverses the order of the collection's items, preserving the original keys:

$collection = collect(['a', 'b', 'c', 'd', 'e']);

$reversed = $collection->reverse();

$reversed->all();

/*
    [
        4 => 'e',
        3 => 'd',
        2 => 'c',
        1 => 'b',
        0 => 'a',
    ]
*/
Enter fullscreen mode Exit fullscreen mode

search()
The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned:

$collection = collect([2, 4, 6, 8]);

$collection->search(4);
Enter fullscreen mode Exit fullscreen mode

// 1

The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use "strict" comparison, pass true as the second argument to the method:

collect([2, 4, 6, 8])->search('4', $strict = true);
Enter fullscreen mode Exit fullscreen mode

// false

Alternatively, you may provide your own closure to search for the first item that passes a given truth test:

collect([2, 4, 6, 8])->search(function ($item, $key) {
    return $item > 5;
});
Enter fullscreen mode Exit fullscreen mode
// 2
Enter fullscreen mode Exit fullscreen mode

shift()
The shift method removes and returns the first item from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

You may pass an integer to the shift method to remove and return multiple items from the beginning of a collection:

$collection = collect([1, 2, 3, 4, 5]);

$collection->shift(3);

// collect([1, 2, 3])

$collection->all();

// [4, 5]

Enter fullscreen mode Exit fullscreen mode

shuffle()
The shuffle method randomly shuffles the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)
Enter fullscreen mode Exit fullscreen mode

skip()
The skip method returns a new collection, with the given number of elements removed from the beginning of the collection:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$collection = $collection->skip(4);

$collection->all();
Enter fullscreen mode Exit fullscreen mode

// [5, 6, 7, 8, 9, 10]

skipUntil()
The skipUntil method skips over items from the collection until the given callback returns true and then returns the remaining items in the collection as a new collection instance:

$collection = collect([1, 2, 3, 4]);

$subset = $collection->skipUntil(function ($item) {
    return $item >= 3;
});

$subset->all();
Enter fullscreen mode Exit fullscreen mode

// [3, 4]

You may also pass a simple value to the skipUntil method to skip all items until the given value is found:

$collection = collect([1, 2, 3, 4]);

$subset = $collection->skipUntil(3);

$subset->all();
Enter fullscreen mode Exit fullscreen mode

// [3, 4]

If the given value is not found or the callback never returns true, the skipUntil method will return an empty collection.

skipWhile()
The skipWhile method skips over items from the collection while the given callback returns true and then returns the remaining items in the collection as a new collection:

$collection = collect([1, 2, 3, 4]);

$subset = $collection->skipWhile(function ($item) {
    return $item <= 3;
});

$subset->all();
Enter fullscreen mode Exit fullscreen mode

// [4]

If the callback never returns false, the skipWhile method will return an empty collection.

slice()
The slice method returns a slice of the collection starting at the given index:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$slice = $collection->slice(4);

$slice->all();

// [5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method:

$slice = $collection->slice(4, 2);

$slice->all();
Enter fullscreen mode Exit fullscreen mode

// [5, 6]

The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the values method to reindex them.

sliding()
The sliding method returns a new collection of chunks representing a "sliding window" view of the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);

$chunks = $collection->sliding(2);

$chunks->toArray();
Enter fullscreen mode Exit fullscreen mode

// [[1, 2], [2, 3], [3, 4], [4, 5]]

This is especially useful in conjunction with the eachSpread method:

$transactions->sliding(2)->eachSpread(function ($previous, $current) {
    $current->total = $previous->total + $current->amount;
});
Enter fullscreen mode Exit fullscreen mode

You may optionally pass a second "step" value, which determines the distance between the first item of every chunk:

$collection = collect([1, 2, 3, 4, 5]);

$chunks = $collection->sliding(3, step: 2);

$chunks->toArray();
Enter fullscreen mode Exit fullscreen mode

// [[1, 2, 3], [3, 4, 5]]

sole()
The sole method returns the first element in the collection that passes a given truth test, but only if the truth test matches exactly one element:

collect([1, 2, 3, 4])->sole(function ($value, $key) {
    return $value === 2;
});
Enter fullscreen mode Exit fullscreen mode

// 2

You may also pass a key / value pair to the sole method, which will return the first element in the collection that matches the given pair, but only if it exactly one element matches:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->sole('product', 'Chair');
Enter fullscreen mode Exit fullscreen mode

// ['product' => 'Chair', 'price' => 100]

Alternatively, you may also call the sole method with no argument to get the first element in the collection if there is only one element:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
]);

$collection->sole();

// ['product' => 'Desk', 'price' => 200]
Enter fullscreen mode Exit fullscreen mode

If there are no elements in the collection that should be returned by the sole method, an \Illuminate\Collections\ItemNotFoundException exception will be thrown. If there is more than one element that should be returned, an \Illuminate\Collections\MultipleItemsFoundException will be thrown.

some()
Alias for the contains method.

sort()
The sort method sorts the collection. The sorted collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([5, 3, 1, 2, 4]);

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm. Refer to the PHP documentation on uasort, which is what the collection's sort method calls utilizes internally.

If you need to sort a collection of nested arrays or objects, see the sortBy and sortByDesc methods.

sortBy()
The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

The sortBy method accepts sort flags as its second argument:

$collection = collect([
    ['title' => 'Item 1'],
    ['title' => 'Item 12'],
    ['title' => 'Item 3'],
]);

$sorted = $collection->sortBy('title', SORT_NATURAL);

$sorted->values()->all();

/*
    [
        ['title' => 'Item 1'],
        ['title' => 'Item 3'],
        ['title' => 'Item 12'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

Alternatively, you may pass your own closure to determine how to sort the collection's values:

$collection = collect([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

If you would like to sort your collection by multiple attributes, you may pass an array of sort operations to the sortBy method. Each sort operation should be an array consisting of the attribute that you wish to sort by and the direction of the desired sort:

$collection = collect([
    ['name' => 'Taylor Otwell', 'age' => 34],
    ['name' => 'Abigail Otwell', 'age' => 30],
    ['name' => 'Taylor Otwell', 'age' => 36],
    ['name' => 'Abigail Otwell', 'age' => 32],
]);

$sorted = $collection->sortBy([
    ['name', 'asc'],
    ['age', 'desc'],
]);

$sorted->values()->all();

/*
    [
        ['name' => 'Abigail Otwell', 'age' => 32],
        ['name' => 'Abigail Otwell', 'age' => 30],
        ['name' => 'Taylor Otwell', 'age' => 36],
        ['name' => 'Taylor Otwell', 'age' => 34],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

When sorting a collection by multiple attributes, you may also provide closures that define each sort operation:

$collection = collect([
    ['name' => 'Taylor Otwell', 'age' => 34],
    ['name' => 'Abigail Otwell', 'age' => 30],
    ['name' => 'Taylor Otwell', 'age' => 36],
    ['name' => 'Abigail Otwell', 'age' => 32],
]);

$sorted = $collection->sortBy([
    fn ($a, $b) => $a['name'] <=> $b['name'],
    fn ($a, $b) => $b['age'] <=> $a['age'],
]);

$sorted->values()->all();

/*
    [
        ['name' => 'Abigail Otwell', 'age' => 32],
        ['name' => 'Abigail Otwell', 'age' => 30],
        ['name' => 'Taylor Otwell', 'age' => 36],
        ['name' => 'Taylor Otwell', 'age' => 34],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

sortByDesc()
This method has the same signature as the sortBy method, but will sort the collection in the opposite order.

sortDesc()
This method will sort the collection in the opposite order as the sort method:

$collection = collect([5, 3, 1, 2, 4]);

$sorted = $collection->sortDesc();

$sorted->values()->all();
Enter fullscreen mode Exit fullscreen mode

// [5, 4, 3, 2, 1]

Unlike sort, you may not pass a closure to sortDesc. Instead, you should use the sort method and invert your comparison.

sortKeys()
The sortKeys method sorts the collection by the keys of the underlying associative array:


$collection = collect([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);

$sorted = $collection->sortKeys();

$sorted->all();

/*
    [
        'first' => 'John',
        'id' => 22345,
        'last' => 'Doe',
    ]
*/
Enter fullscreen mode Exit fullscreen mode

sortKeysDesc()
This method has the same signature as the sortKeys method, but will sort the collection in the opposite order.

sortKeysUsing()
The sortKeysUsing method sorts the collection by the keys of the underlying associative array using a callback:

$collection = collect([
    'ID' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);

$sorted = $collection->sortKeysUsing('strnatcasecmp');

$sorted->all();

/*
    [
        'first' => 'John',
        'ID' => 22345,
        'last' => 'Doe',
    ]
*/
Enter fullscreen mode Exit fullscreen mode

The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on uksort, which is the PHP function that sortKeysUsing method utilizes internally.

splice()
The splice method removes and returns a slice of items starting at the specified index:

$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2);

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]
Enter fullscreen mode Exit fullscreen mode

You may pass a second argument to limit the size of the resulting collection:

$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]
Enter fullscreen mode Exit fullscreen mode

In addition, you may pass a third argument containing the new items to replace the items removed from the collection:

$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();
Enter fullscreen mode Exit fullscreen mode

// [1, 2, 10, 11, 4, 5]

split()
The split method breaks a collection into the given number of groups:

$collection = collect([1, 2, 3, 4, 5]);

$groups = $collection->split(3);

$groups->all();
Enter fullscreen mode Exit fullscreen mode

// [[1, 2], [3, 4], [5]]

splitIn()
The splitIn method breaks a collection into the given number of groups, filling non-terminal groups completely before allocating the remainder to the final group:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$groups = $collection->splitIn(3);

$groups->all();
Enter fullscreen mode Exit fullscreen mode
`// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]`
Enter fullscreen mode Exit fullscreen mode

sum()
The sum method returns the sum of all items in the collection:

collect([1, 2, 3, 4, 5])->sum();

// 15
Enter fullscreen mode Exit fullscreen mode

If the collection contains nested arrays or objects, you should pass a key that will be used to determine which values to sum:

$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);

$collection->sum('pages');

// 1272
Enter fullscreen mode Exit fullscreen mode

In addition, you may pass your own closure to determine which values of the collection to sum:

$collection = collect([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$collection->sum(function ($product) {
    return count($product['colors']);
});

// 6
Enter fullscreen mode Exit fullscreen mode

take()
The take method returns a new collection with the specified number of items:

$collection = collect([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]
Enter fullscreen mode Exit fullscreen mode

You may also pass a negative integer to take the specified number of items from the end of the collection:

$collection = collect([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(-2);

$chunk->all();

// [4, 5]
Enter fullscreen mode Exit fullscreen mode

takeUntil()
The takeUntil method returns items in the collection until the given callback returns true:

$collection = collect([1, 2, 3, 4]);

$subset = $collection->takeUntil(function ($item) {
    return $item >= 3;
});

$subset->all();

// [1, 2]
Enter fullscreen mode Exit fullscreen mode

You may also pass a simple value to the takeUntil method to get the items until the given value is found:

$collection = collect([1, 2, 3, 4]);

$subset = $collection->takeUntil(3);

$subset->all();

// [1, 2]

Enter fullscreen mode Exit fullscreen mode

If the given value is not found or the callback never returns true, the takeUntil method will return all items in the collection.

takeWhile()
The takeWhile method returns items in the collection until the given callback returns false:

$collection = collect([1, 2, 3, 4]);

$subset = $collection->takeWhile(function ($item) {
    return $item < 3;
});

$subset->all();

// [1, 2]
Enter fullscreen mode Exit fullscreen mode

If the callback never returns false, the takeWhile method will return all items in the collection.

tap()
The tap method passes the collection to the given callback, allowing you to "tap" into the collection at a specific point and do something with the items while not affecting the collection itself. The collection is then returned by the tap method:

collect([2, 4, 3, 1, 5])
    ->sort()
    ->tap(function ($collection) {
        Log::debug('Values after sorting', $collection->values()->all());
    })
    ->shift();

// 1
Enter fullscreen mode Exit fullscreen mode

times()
The static times method creates a new collection by invoking the given closure a specified number of times:

$collection = Collection::times(10, function ($number) {
    return $number * 9;
});

$collection->all();

// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
Enter fullscreen mode Exit fullscreen mode

toArray()
The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays:

$collection = collect(['name' => 'Desk', 'price' => 200]);

$collection->toArray();

/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw array underlying the collection, use the all method instead.

toJson()
The toJson method converts the collection into a JSON serialized string:

$collection = collect(['name' => 'Desk', 'price' => 200]);

$collection->toJson();

// '{"name":"Desk", "price":200}'
Enter fullscreen mode Exit fullscreen mode

transform()
The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:

$collection = collect([1, 2, 3, 4, 5]);

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Unlike most other collection methods, transform modifies the collection itself. If you wish to create a new collection instead, use the map method.

undot()
The undot method expands a single-dimensional collection that uses "dot" notation into a multi-dimensional collection:

$person = collect([
    'name.first_name' => 'Marie',
    'name.last_name' => 'Valentine',
    'address.line_1' => '2992 Eagle Drive',
    'address.line_2' => '',
    'address.suburb' => 'Detroit',
    'address.state' => 'MI',
    'address.postcode' => '48219'
]);

$person = $person->undot();

$person->toArray();

/*
    [
        "name" => [
            "first_name" => "Marie",
            "last_name" => "Valentine",
        ],
        "address" => [
            "line_1" => "2992 Eagle Drive",
            "line_2" => "",
            "suburb" => "Detroit",
            "state" => "MI",
            "postcode" => "48219",
        ],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

union()
The union method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection's values will be preferred:

$collection = collect([1 => ['a'], 2 => ['b']]);

$union = $collection->union([3 => ['c'], 1 => ['d']]);

$union->all();

// [1 => ['a'], 2 => ['b'], 3 => ['c']]
Enter fullscreen mode Exit fullscreen mode

unique()
The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([1, 1, 2, 2, 3, 4, 2]);

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

When dealing with nested arrays or objects, you may specify the key used to determine uniqueness:

$collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);

$unique = $collection->unique('brand');

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

Finally, you may also pass your own closure to the unique method to specify which value should determine an item's uniqueness:

$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

The unique method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the uniqueStrict method to filter using "strict" comparisons.

This method's behavior is modified when using Eloquent Collections.

uniqueStrict()
This method has the same signature as the unique method; however, all values are compared using "strict" comparisons.

unless()
The unless method will execute the given callback unless the first argument given to the method evaluates to true:

$collection = collect([1, 2, 3]);

$collection->unless(true, function ($collection) {
    return $collection->push(4);
});

$collection->unless(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

A second callback may be passed to the unless method. The second callback will be executed when the first argument given to the unless method evaluates to true:

$collection = collect([1, 2, 3]);

$collection->unless(true, function ($collection) {
    return $collection->push(4);
}, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

For the inverse of unless, see the when method.

unlessEmpty()
Alias for the whenNotEmpty method.

unlessNotEmpty()
Alias for the whenEmpty method.

unwrap()
The static unwrap method returns the collection's underlying items from the given value when applicable:

Collection::unwrap(collect('John Doe'));

// ['John Doe']

Collection::unwrap(['John Doe']);

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'
Enter fullscreen mode Exit fullscreen mode

value()
The value method retrieves a given value from the first element of the collection:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Speaker', 'price' => 400],
]);

$value = $collection->value('price');

// 200
Enter fullscreen mode Exit fullscreen mode

values()
The values method returns a new collection with the keys reset to consecutive integers:

$collection = collect([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200],
]);

$values = $collection->values();

$values->all();

/*
    [
        0 => ['product' => 'Desk', 'price' => 200],
        1 => ['product' => 'Desk', 'price' => 200],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

when()
The when method will execute the given callback when the first argument given to the method evaluates to true. The collection instance and the first argument given to the when method will be provided to the closure:

$collection = collect([1, 2, 3]);

$collection->when(true, function ($collection, $value) {
    return $collection->push(4);
});

$collection->when(false, function ($collection, $value) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

A second callback may be passed to the when method. The second callback will be executed when the first argument given to the when method evaluates to false:

$collection = collect([1, 2, 3]);

$collection->when(false, function ($collection, $value) {
    return $collection->push(4);
}, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

For the inverse of when, see the unless method.

whenEmpty()
The whenEmpty method will execute the given callback when the collection is empty:

$collection = collect(['Michael', 'Tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('Adam');
});

$collection->all();

// ['Michael', 'Tom']


$collection = collect();

$collection->whenEmpty(function ($collection) {
    return $collection->push('Adam');
});

$collection->all();

// ['Adam']
Enter fullscreen mode Exit fullscreen mode

A second closure may be passed to the whenEmpty method that will be executed when the collection is not empty:

$collection = collect(['Michael', 'Tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('Adam');
}, function ($collection) {
    return $collection->push('Taylor');
});

$collection->all();

// ['Michael', 'Tom', 'Taylor']
Enter fullscreen mode Exit fullscreen mode

For the inverse of whenEmpty, see the whenNotEmpty method.

whenNotEmpty()
The whenNotEmpty method will execute the given callback when the collection is not empty:

$collection = collect(['michael', 'tom']);

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// ['michael', 'tom', 'adam']


$collection = collect();

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// []

A second closure may be passed to the whenNotEmpty method that will be executed when the collection is empty:

$collection = collect();

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
}, function ($collection) {
    return $collection->push('taylor');
});

$collection->all();

// ['taylor']
Enter fullscreen mode Exit fullscreen mode

For the inverse of whenNotEmpty, see the whenEmpty method.

where()
The where method filters the collection by a given key / value pair:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

The where method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereStrict method to filter using "strict" comparisons.

Optionally, you may pass a comparison operator as the second parameter. Supported operators are: '===', '!==', '!=', '==', '=', '<>', '>', '<', '>=', and '<=':


$collection = collect([
    ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
    ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ['name' => 'Sue', 'deleted_at' => null],
]);

$filtered = $collection->where('deleted_at', '!=', null);

$filtered->all();

/*
    [
        ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
        ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

whereStrict()
This method has the same signature as the where method; however, all values are compared using "strict" comparisons.

whereBetween()
The whereBetween method filters the collection by determining if a specified item value is within a given range:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereBetween('price', [100, 200]);

$filtered->all();

/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

whereIn()
The whereIn method removes elements from the collection that do not have a specified item value that is contained within the given array:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

The whereIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereInStrict method to filter using "strict" comparisons.

whereInStrict()
This method has the same signature as the whereIn method; however, all values are compared using "strict" comparisons.

whereInstanceOf()
The whereInstanceOf method filters the collection by a given class type:

use App\Models\User;
use App\Models\Post;

$collection = collect([
    new User,
    new User,
    new Post,
]);

$filtered = $collection->whereInstanceOf(User::class);

$filtered->all();
Enter fullscreen mode Exit fullscreen mode

// [App\Models\User, App\Models\User]

whereNotBetween()
The whereNotBetween method filters the collection by determining if a specified item value is outside of a given range:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotBetween('price', [100, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 80],
        ['product' => 'Pencil', 'price' => 30],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

whereNotIn()
The whereNotIn method removes elements from the collection that have a specified item value that is contained within the given array:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

The whereNotIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereNotInStrict method to filter using "strict" comparisons.

whereNotInStrict()
This method has the same signature as the whereNotIn method; however, all values are compared using "strict" comparisons.

whereNotNull()
The whereNotNull method returns items from the collection where the given key is not null:

$collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNotNull('name');

$filtered->all();

/*
    [
        ['name' => 'Desk'],
        ['name' => 'Bookcase'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

whereNull()
The whereNull method returns items from the collection where the given key is null:

$collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNull('name');

$filtered->all();

/*
    [
        ['name' => null],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)