Introduction
Laravel’s collection class provides a fluent, convenient wrapper for working with arrays of data. In this tutorial, we will explore how you can utilize collections in the Laravel framework by looking at a variety of examples. This guide will take you from the basics to more advanced uses, showing how collections can make your code more readable, maintainable, and efficient.
Basic Usage of Collections
To start with collections, let’s first understand how to create them. You can create a collection instance from an array using the collect
helper function:
$collection = collect([1, 2, 3, 4, 5]);
Once you have a collection, you have a variety of methods at your disposal. Here’s an example of using the each
method to iterate over items:
$collection->each(function ($item, $key) {
echo $item;
});
// Output: 12345
You can also perform operations like map
, filter
, and reduce
that allow you to manipulate the collection data easily.
Transforming Collections
The map
method applies a callback function to each item and returns a new collection with the items transformed:
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
// Output: [2, 4, 6, 8, 10]
Filtering is another powerful feature. For instance, the filter
method removes items based on a condition:
$filtered = $collection->filter(function ($value) {
return $value > 3;
});
// Output: [4, 5]
Collection Keys and Values
You can also work with the keys of the collection using methods such as keys
to obtain the collection’s keys:
$collection = collect([
'name' => 'John',
'email' => '[email protected]'
]);
$keys = $collection->keys();
// Output: ['name', 'email']
To get the values without keys:
$values = $collection->values();
// Output: ['John', '[email protected]']
Advanced Collection Methods
Laravel collections offer more advanced methods, such as groupBy
, that allow you to group items by a given key:
$collection = collect([
['product' => 'Apples', 'price' => 50],
['product' => 'Oranges', 'price' => 60],
['product' => 'Apples', 'price' => 70]
]);
$grouped = $collection->groupBy('product');
// Output: ['Apples' => [[...], [...]], 'Oranges' => [[...]]]
Combine them with other methods like sum
can give powerful insights:
$totalPrices = $grouped->map(function ($item, $key) {
return $item->sum('price');
});
// Output: ['Apples' => 120, 'Oranges' => 60]
Working with JSON
Collections can easily be converted to JSON for use with APIs or JavaScript:
$collection = collect(['name' => 'John', 'email' => '[email protected]']);
$json = $collection->toJson();
// Output: '{"name":"John","email":"[email protected]"}'
Lazy Collections
For dealing with extremely large datasets, you can take advantage of lazy collections introduced in Laravel. They allow you to work with a very large amount of data efficiently:
$lazyCollection =
\\\Illuminate\\\Support\\\LazyCollection::make(function () {
for ($i = 0; $i < 1000000; $i++) {
yield $i;
}
});
// Use the collection without loading all elements into memory
Conclusion
Throughout this tutorial, we’ve explored various functionalities of Laravel collections from simple iteration to complex transformations and lazy loading. Understanding these concepts helps write cleaner and more efficient code, leveraging the full power of Laravel’s collections for elegant data handling.