Collections in laravel

Collections in laravel

The Collection class in Laravel is really awesome. In Laravel, database query results are actually returned as a collection object, that contains the actual results. The class contains a lot of handy methods that will make your work so much easier.

When I’m working with external API’s, I often wrap the results in a collection so that I can use those methods:

These are a few methods that I use quite often:


This method will return every value of a given key. The following example returns every user’s email address, indexed by their user id.

I use it to get values to pass to a whereIn query, to get data for a pie chart or to pass data to a dropdown menu.


This will run a filter function over each of the items. If the callback returns true, it will be present in the resulting collection.

Most of the time you will be able to limit the results straight from the query, but in some cases this will come in handy when the filter is pretty difficult, when you’re working on a cached collection or when you want to filter API results.


Another great thing about collections is that they can easily be converted to json.

When you cast a collection to a string, it will actually call the toJson method:


Something that’s quite obvious is the count method, which just returns you how many items there are in the collection. One important thing to note here is that if you are using relations, execute the count method on the builder object and not on the collection object:

And not:

That last example will first get all the post object of that user and wrap it in a collection, then the count method will tell you how many items there are in that collection. The first example however, will perform a count database query that will return the result a lot faster.


Works just like the query builder, takes the first or last number of items.


The sum method will return the sum based on the key or a callback function:

SortBy and sortByDesc

You can use sortBy or sortByDesc to sort the collection based on a key or a callback function. The first parameter is your key of the callback function, the second one is the sorting method (


There are a few more methods that you can see over here:

If you like this article, Please don’t forget to share and comment.

Thanks!. Happy coding.