What about collections

collections ? Hell yeah ! Arrays on steroids in my humble opinion ... I'll tell you why

2 minutes

What about collections

What are collections ?

Collections are a Laravel wrapper for arrays to work with data in a fluent and expressive way. The collection methods are chainable and give you a very powerful toolset for working with data.


Collections provide their power via self explanatory methods. The full list of available method can be found in the documentation.

An example of a method is the "sum" , making it extreme simple to take the sum of all elements in an array

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


An extra power of collections is that they can be chained , which means that you can execute a chain of actions on a collection retreiving the results in one code flow. Like in the example below with groupby , map and sum.

Why I think you should use collections

Every method on a collection uses underlaying array logic. So you could achieve the same result when using arrays. But collections provide you with a much more discriptive way of programming. The code is mostly self explanatory and much easier to understand. Not only for you as a developer, but also for team members reviewing your code or adapting your code. I'll give you an example. Assume you want to get the sum of the price of the lines in an offer grouped by the group the lines are in.

You could achieve it like this with an array

$totalPerGroup = []; if (count($offer->lines) > 0) { foreach ($offer->lines as $line) { if (isset($totalPerGroup[$line->group])){ $totalPerGroup[$line->group] += $line->price; }else{ $totalPerGroup[$line->group] = $line->price; } } }

This is a perfect working example , but it can be done much more readable and descriptive if you use collections

$totalPerGroup = collect($offer->lines)->groupBy('group')->map( fn($group) => $group->sum('price') );

By readling this code it explains what it does , giving you the extra advantage that you have to write less documentation in your code.

Easily expandable

Collections are "macroable", which allows you to add additional methods to the Collection class at run time. With this power you can write your own collection methods making your custom logic even more readable and reusable.

My top used collection methods

If I think about which methods I use the most I see myself using these : filter, where, transform, sum, each, keyBy, groupBy, sortBy, toArray, values . Of course I use more than only these , but these are my top 10.

this article has been read 6 times