Amazing laravel collection methods

Introduction

Laravel Collection class provides a fluent , convenient wrapper for working with arrays of data. Collection provides powerful methods like filter, map and many other which makes working with array easy.

Let’s see an example :

We just need to wrap the array with helper function collect() and the collect helper will returns a new Illuminate\Support\Collection instance for the given array.

The results of Eloquent queries are always returned as Collection instances. — Laravel

We will be using below collection data to play around.

filter()

filter() allows us to filter the collection with a callback. It will only return those items which passes the test.

Pretty cool right ? 🙂

map()

map() will iterates through each collection and passes each value to the given callback. The callback can modify the item and return them .

These helpers will ease out your day to day work. I frequently used them . Some other helpful methods :

pluck()

pluck() is very helpful, this allows us to pluck a value of a given key.

contains()

contains() method simply checks if given value is available in the collection.

merge()

merge() method simply allows us merge the given array or collection with the original collection.

toArray()

toArray() method converts the collection into plain PHP array.

tap()

tap() method on collections that allows us to tap on specific point and do something. This does not affect the result of our main collection. This is pretty useful while debugging our code.

We have tried out to cover some of the most used collection methods but there is still many useful methods left out. If found useful do share with your friends and keep coding 🙂

 

Sharing is caring!

Related Post