Introduction
Laravel collections provide a fluent, convenient wrapper for working with arrays of data. They are part of Laravel’s Illuminate\Support
library and offer a variety of methods to transform, filter, and manipulate data efficiently.
What Are Laravel Collections?
A collection in Laravel is a PHP class (Illuminate\Support\Collection
) that provides a set of methods for working with arrays or objects. Collections can be created from arrays, database query results, or other iterable objects.
Creating a Collection
use Illuminate\Support\Collection;
// Creating a collection from an array
$collection = collect([1, 2, 3, 4, 5]);
// Creating a collection from a model query
$users = User::all(); // Returns a collection of users
Commonly Used Methods
1. filter()
Filters items in the collection based on a callback.
$collection = collect([1, 2, 3, 4, 5]);
$filtered = $collection->filter(function ($value) {
return $value > 3;
});
// Result: [4, 5]
2. map()
Applies a callback to each item in the collection and returns a new collection.
$collection = collect([1, 2, 3]);
$mapped = $collection->map(function ($value) {
return $value * 2;
});
// Result: [2, 4, 6]
3. pluck()
Retrieves a specific key’s values from a collection of arrays or objects.
$users = collect([
['name' => 'Alice', 'email' => '[email protected]'],
['name' => 'Bob', 'email' => '[email protected]'],
]);
$emails = $users->pluck('email');
// Result: ['[email protected]', '[email protected]']
4. reduce()
Reduces the collection to a single value using a callback.
$collection = collect([1, 2, 3, 4]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 0);
// Result: 10
5. sort()
and sortBy()
Sorts the collection by its values or a specified key.
$collection = collect([5, 3, 1, 4, 2]);
$sorted = $collection->sort();
// Result: [1, 2, 3, 4, 5]
$users = collect([
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
]);
$sortedByAge = $users->sortBy('age');
// Result: [['name' => 'Bob', 'age' => 25], ['name' => 'Alice', 'age' => 30]]
6. groupBy()
Groups items in the collection by a specified key.
$users = collect([
['name' => 'Alice', 'role' => 'admin'],
['name' => 'Bob', 'role' => 'user'],
['name' => 'Charlie', 'role' => 'admin'],
]);
$grouped = $users->groupBy('role');
// Result:
// [
// 'admin' => [
// ['name' => 'Alice', 'role' => 'admin'],
// ['name' => 'Charlie', 'role' => 'admin'],
// ],
// 'user' => [
// ['name' => 'Bob', 'role' => 'user'],
// ],
// ]
7. toArray()
and toJson()
Converts the collection to an array or JSON string.
$collection = collect(['name' => 'Alice', 'email' => '[email protected]']);
$array = $collection->toArray();
$json = $collection->toJson();
// Result:
// Array: ['name' => 'Alice', 'email' => '[email protected]']
// JSON: '{"name":"Alice","email":"[email protected]"}'
Chaining Methods
Collections allow method chaining, making complex operations concise and readable.
$users = collect([
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35],
]);
$result = $users->filter(function ($user) {
return $user['age'] > 25;
})
->pluck('name')
->sort()
->values();
// Result: ['Alice', 'Charlie']
Best Practices for Using Collections
-
Leverage Lazy Collections: For large datasets, use
LazyCollection
to reduce memory usage.$collection = LazyCollection::make(function () { foreach (range(1, 1000000) as $number) { yield $number; } });
-
Eager Load Relationships: When working with related data, use
with()
to prevent N+1 query issues.$users = User::with('posts')->get();
-
Avoid Overusing Collections: Use raw queries or query builder for complex operations that don’t benefit from collections.
Helpful Resources
Official Documentation
Tutorials
Conclusion
Laravel collections provide an expressive and powerful way to handle data manipulation. By mastering collection methods and applying best practices, you can write cleaner, more efficient, and readable code for your Laravel applications.