Loading...

Laravel Collection Class: The New Way to Interact with ArraysThe PHP language has a large set of functions used for processing and modifying arrays. However, I was recently introduced to the Illuminate\Support\Collection class produced also know as Laravel Collection Class. The Laravel Collection class allows us to interact with array’s in a fluent interface and can even be used in non-Laravel projects without having to import the entire Illuminate/Support package.

Here are some examples of how the Laravel Collection Class improves our experience.

Old Way to Interact with Arrays:


// Old way
$array = ['apple', 'pear', 1, 2, 'banana', 'celery', 'carrot'];
// Remove any integer values
$newArray = array_filter($array, function ($item) {
  return !is_integer($item);
}
);
// Remove any vegetables.
$newArray = array_filter($newArray, function ($item) {
  return !in_array($item, ['carrot', 'celery']);
});
sort($newArray);
$newArray = array_map(function ($item) {
  return ucfirst($item);
},
  $newArray
);

Introducing Laravel Collection Class: 


// New way!
$array = ['apple', 'pear', 1, 2, 'banana', 'celery', 'carrot'];
$collection = collect($array)
  ->filter(function ($item) {
    return !is_integer($item);
  })
  ->reject(function ($item) {
    return in_array($item, ['carrot', 'celery']);
  })
  ->sort()
  ->map(function ($item) {
    return ucfirst($item);
  })
  ->toArray();

Output:


Array
(
    [0] => Apple
    [1] => Banana
    [2] => Pear
)

As you can see, the Collection object allows us to chain methods together, providing us a fluent, easy-to-read interface. It also benefits from the standard OOP in that it can be extended to include additional functionality. Check out the documentation to sort through all the great functionality the Collection objection can offer.