10 Helpful Methods That You Can Use On Laravel Collections
Handy methods that you can use to get the most out of a Laravel Collection
The Collection class in Laravel provides a really nice wrapper for working with arrays. Every Laravel developer has used the Collection class more than once, especially when working with Eloquent. In this article, I will be giving you 10 helpful methods that you can use to get the most out of your Laravel Collection.
1. Checking for duplicates
The duplicates method retrieves all duplicate values in a collection. The resulting array will have the original keys.
2. Looping over a collection
It is possible to loop over a collection without using a
foreach. This can be done by using the
each method. The
each method has two parameters, item and key, just like a normal
3. Debugging a collection
Dumping the content of a collection is very important when it comes to debugging. Instead of using
dump($collection), the Collection class has its own dump method, which has a much cleaner output.
If you want the script to exit after dumping the collection, you can use the
dd (dump and die) method on the collection instead.
The has method can be used to check if a key exists in the collection. You can either pass a string or an array as a parameter. If an array is passed as a parameter, all values of that array have to exist as keys in the collection.
The implode method makes it possible to join the items of a collection. This works exactly the same as PHP’s implode function.
If the collection contains only strings or numeric values you only have to pass the glue argument.
6. Push and Pull
Appending an item to the end of the collection can be done by using the push method. If you want to add an item to the beginning of the collection you can use the
The pull method removes and returns an item from the collection by its key.
The shuffle method shuffles the items of the collection in random order.
You can get the maximum value of a collection by using the max method. If the collection contains arrays, you can pass a parameter to get the maximum value of a certain key.
A collection can be filtered using the filter method. The filter method uses a callback. Only the items that pass a given check, will be kept in the collection.
The slice method returns a slice of the collection starting at the index that is passed as a parameter. The resulting array will have the original keys.
Note that in the example below the parameter 2 is passed. This means that the sliced collection will start at index 2 and not at element 2.
These are the ten Collection methods that I wanted to share with you. Please share your thoughts on this article. Make sure to check out my other posts as well. A lot of my content is about Laravel. Feel free to leave a comment if you have any feedback, questions or want me to write about another Laravel related topic.