Top 10 Laravel Collection Methods You May Have Never Used


Laravel Collections are an integral part of the framework, offering a fluent, convenient wrapper for working with arrays of data. While many developers are familiar with the basics, Laravel Collections offers many lesser-known methods that can significantly streamline your code and enhance productivity. Here are the top 10 Laravel Collection methods you may have never used:


1. `pluck`


The `pluck` method retrieves all of the values for a given key from an array or collection of arrays.


Example:

$users = collect([

    ['name' => 'John', 'email' => 'john@example.com'],

    ['name' => 'Jane', 'email' => 'jane@example.com'],

]);


$emails = $users->pluck('email');


// ['john@example.com', 'jane@example.com']


2. `partition`


The `partition` method may be used to separate elements that pass a given truth test from those that do not.


Example:

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


list($even, $odd) = $collection->partition(function ($i) {

    return $i % 2 === 0;

});


// $even: [2, 4, 6]

// $odd: [1, 3, 5]


3. `mapWithKeys`


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


Example:

$collection = collect([

    ['name' => 'John', 'email' => 'john@example.com'],

    ['name' => 'Jane', 'email' => 'jane@example.com'],

]);


$keyed = $collection->mapWithKeys(function ($item) {

    return [$item['email'] => $item['name']];

});


// ['john@example.com' => 'John', 'jane@example.com' => 'Jane']


4. `eachSpread`


The `eachSpread` method iterates over the collection's items and passes each nested array item into a callback as individual arguments.


Example:

$collection = collect([

    [1, 'John'],

    [2, 'Jane'],

]);


$collection->eachSpread(function ($id, $name) {

    echo "$id: $name";

});


// 1: John

// 2: Jane


5. `reject`


The `reject` method filters the collection using the given callback, removing the elements that pass the given truth test.


Example:

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


$filtered = $collection->reject(function ($value) {

    return $value > 2;

});


// [1, 2]


6. `tap`


The `tap` method passes the collection to the given callback and then returns the collection.


Example:

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


$collection->tap(function ($col) {

    // Log the collection, or perform other actions

    Log::info($col);

})->sort();


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


7. `crossJoin`


The `crossJoin` method cross joins the collection with the given arrays, returning a Cartesian product.


Example:

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


$matrix = $collection->crossJoin(['A', 'B']);


// [[1, 'A'], [1, 'B'], [2, 'A'], [2, 'B']]


8. `pipe`


The `pipe` method passes the collection to the given callback and returns the result.


Example:

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


$piped = $collection->pipe(function ($col) {

    return $col->sum();

});


// 6


9. `flatMap`


The `flatMap` method iterates through the collection and passes each value to the given callback. The callback should return an array of key/value pairs, which will be flattened into a single array.


Example:

$collection = collect([

    ['name' => 'John', 'hobbies' => ['Reading', 'Swimming']],

    ['name' => 'Jane', 'hobbies' => ['Cycling']],

]);


$hobbies = $collection->flatMap(function ($item) {

    return $item['hobbies'];

});


// ['Reading', 'Swimming', 'Cycling']


10. `whenEmpty` and `whenNotEmpty`


The `whenEmpty` method executes the given callback when the collection is empty, while `whenNotEmpty` does the opposite.


Example:

$collection = collect([]);


$collection->whenEmpty(function ($col) {

    return $col->push('Default Value');

});


// ['Default Value']


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


$collection->whenNotEmpty(function ($col) {

    return $col->push(4);

});


// [1, 2, 3, 4]



Laravel Collections offer an impressive array of methods beyond the basics. By exploring and utilizing these lesser-known methods like `pluck`, `partition`, `mapWithKeys`, `eachSpread`, `reject`, `tap`, `crossJoin`, `pipe`, `flatMap`, and the `whenEmpty/whenNotEmpty` pair, you can write more concise, readable, and efficient code. Dive into the Laravel documentation and experiment with these methods to unlock their full potential.