Laravel Collections

Laravel collections allow you to work efficiently with arrays. Basically you take arrays as input and it will create Illuminate\Support\Collection object once you have the object available than you can perform different types of array operations on the object.

It helps you reduce your messy code without if/else statements and code looks more pretty and redable to developers. In this tutorial we will learn about collections and will see howt it can help us to reduce our day to day work.

How to filter null values from the array in Laravel?

In following example we will supply array to collect function, collect function will return object of type Illuminate\Support\Collection than you can perform different types of operations on the Collection object and later you can return modified array as output.

// returns object of type Illuminate\Support\Collection
$collection = collect(['sandip', 'chintu', null]);

// loop through collection make all values uppercase
// use reject function reject array values that are empty
$array = $collection
->map(function ($value) {
        return Str::upper($value);
    })
    ->reject(function ($name) {
        return empty($name);
    })->toArray();
    
// print the array
dd($array);

// OUTPUT: ['SANDIP', 'CHINTU']

How to calculate average value of array in Laravel?

// create array to laravel collection object
$collection = collect([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
]);

// print average of the collection array
dd($collection->avg());

// OUTPUT: 20

How to create array in batch sizes in Laravel?

// create array to laravel collection object
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

// create array in batch of 5
$batches = $collection->chunk(5);

// display array with batches
dd($batches->all());

// OUTPUT: 

How to flattern multi-dimentional to single array in Laravel?

// create multi-dimentional array to laravel collection
$collection = collect([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]);

// flattern all arrays into single
$collapsed = $collection->collapse();

// display single array
dd($collapsed->all());

// OUTPUT: [1, 2, 3, 4, 5, 6, 7, 8, 9]

How to combine two array with key/value pair in Laravel?

// create array that will be used as keys to laravel collection object
$collection = collect(['name', 'age']);

// supply array that will be used as values
$combined = $collection->combine(['Sandip', 29]);

// display values
dd($combined->all());

// OUTPUT: ['name' => 'Sandip', 'age' => 29]

How to check if value in array meet given criteria in Laravel?

// create array to laravel object
$collection = collect([1, 2, 3, 4, 5]);

// check to see if values in array are greater then 5
$moreThenFive =$collection->contains(function ($value, $key) {
    return $value > 5;
});

dd($moreThenFive); // OUTPUT: false

// create array to collection object
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

// check to see product has value Table
dd($collection->contains('product', 'Table'));

How to perform multiple operations on array in Laravel?

// create employee array to laravel collection
$employees = collect([
      ['email' => 'james@example.com', 'position' => 'Designer'],
      ['email' => 'abigail@example.com', 'position' => 'Developer'],
      ['email' => 'victoria@example.com', 'position' => 'Developer'],
]);

$employees
    // find duplicate positions
    // with total duplicate counts
    ->duplicates('position')

    // make values uppercase
    ->map(function ($value) {
        return Str::upper($value);
    })

    // get all values
    ->all()

    // dump given array
    ->dd();

I hope you enjoyed this tutorial on laravel collection to see list of operations that you can perform on collection object click the link below:

Laravel collection methods