
Laravel Collections | Part 1
In Part 1, we'll delve into a variety of Collection methods, each accompanied by an example:
1. all()
The all
method returns all the items from the collection as a plain array. It's a straightforward way to convert a collection into a standard PHP array.
2. average()
The average
method calculates the average of all numeric values in the collection. It's handy when you need to find the mean value of a set of numbers.
3. avg()
Similar to average()
, the avg
method calculates the average of all numeric values in the collection. It provides an alias for the same functionality.
4. chunk()
The chunk
is a very handy method, it breaks the collection into smaller chunks of a specified size. It's useful for paginating large datasets or processing data in batches.
5. chunkWhile()
The chunkWhile
method allows you to chunk a collection based on a callback function's logic. It chunks the data until the callback returns false
.
6. collapse()
The collapse
method flattens a multi-dimensional collection into a single-dimensional one. It's handy when you have nested arrays and want to simplify the structure.
7. collect()
The collect
function is not a method but a global helper function that converts an array into a collection instance.
8. combine()
The combine
method combines the values of one collection as keys with the values of another collection as values to create a new collection.
9. concat()
The concat
method appends the items of another array or collection to the current collection, creating a new collection.
10. contains()
The contains
method checks if the collection contains a specific value. It returns true
if the value is found, otherwise false
.
11. containsOneItem()
The containsOneItem
method checks if the collection contains only one item. It returns true
if there's exactly one item in the collection.
12. containsStrict()
The containsStrict
method checks if the collection contains a specific value using strict comparison (===). It returns true
if the value is found strictly, otherwise false
.
13. count()
The count
method returns the number of items in the collection.
14. countBy()
The countBy
method groups the collection's items by a key or callback function and returns the count of items in each group as a new collection.
15. crossJoin()
The crossJoin
method returns all possible combinations of the items from multiple arrays or collections, creating a new collection of arrays.
In Part 2, we'll explore more of what Laravel Collections has to offer, enabling you to become a true Collection master in your Laravel projects. Stay tuned and Happy Coding!