Kritim Yantra
Apr 01, 2025
Laravel Collections are one of the most powerful features of the framework, providing a fluent and convenient way to work with arrays of data. Whether you're dealing with database query results or manipulating arrays, Laravel Collections offer a wide range of methods to simplify complex operations.
In this blog post, we'll dive deep into Laravel 12 Collections, covering everything from basic usage to advanced techniques. By the end, you'll have a solid understanding of how to leverage Collections effectively in your Laravel applications.
A Collection in Laravel is a wrapper around an array that provides a fluent, chainable interface for performing common array operations. Collections are inspired by functional programming paradigms and allow you to write cleaner, more expressive code.
You can create a Collection in several ways:
use Illuminate\Support\Collection;
$collection = new Collection([1, 2, 3, 4, 5]);
Or using the collect()
helper:
$collection = collect([1, 2, 3, 4, 5]);
Eloquent queries return Collections by default:
$users = User::all(); // Returns a Collection of User models
$jsonData = '{"name": "John", "age": 30}';
$collection = collect(json_decode($jsonData, true));
all()
– Get the Underlying Array$collection = collect([1, 2, 3]);
$array = $collection->all(); // [1, 2, 3]
count()
– Get the Number of Items$count = $collection->count(); // 3
first()
and last()
– Get First/Last Element$first = $collection->first(); // 1
$last = $collection->last(); // 3
get()
– Retrieve an Item by Key$collection = collect(['name' => 'John', 'age' => 30]);
$name = $collection->get('name'); // 'John'
has()
– Check if Key Existsif ($collection->has('age')) {
echo "Age exists!";
}
filter()
– Keep Items Based on Condition$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
// Result: [3, 4, 5]
reject()
– Remove Items Based on Condition$rejected = $collection->reject(function ($value, $key) {
return $value <= 2;
});
// Result: [3, 4, 5]
sort()
– Sort Items$sorted = $collection->sort();
// Ascending order
sortBy()
– Sort by a Key$users = collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
]);
$sortedByAge = $users->sortBy('age');
// Jane (25), John (30)
map()
– Modify Each Item$multiplied = $collection->map(function ($item) {
return $item * 2;
});
// [2, 4, 6, 8, 10]
pluck()
– Extract a Key’s Value$names = $users->pluck('name');
// ['John', 'Jane']
flatten()
– Convert Nested Arrays to Flat$nested = collect([[1, 2], [3, 4]]);
$flattened = $nested->flatten();
// [1, 2, 3, 4]
sum()
– Calculate Sum$total = $collection->sum(); // 15
avg()
– Calculate Average$average = $collection->avg(); // 3
min()
and max()
– Find Extremes$min = $collection->min(); // 1
$max = $collection->max(); // 5
groupBy()
– Group Items by Key$grouped = $users->groupBy('age');
// Groups users by their age
chunk()
– Split into Smaller Collections$chunks = $collection->chunk(2);
// [[1, 2], [3, 4], [5]]
each()
– Loop Through Items$collection->each(function ($item) {
echo $item;
});
For memory efficiency with large datasets, Laravel provides Lazy Collections:
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
$file = fopen('large-file.txt', 'r');
while ($line = fgets($file)) {
yield $line;
}
})->chunk(1000)->each(function ($lines) {
// Process 1000 lines at a time
});
You can extend Collections with custom methods:
use Illuminate\Support\Collection;
Collection::macro('toUpper', function () {
return $this->map(function ($item) {
return strtoupper($item);
});
});
$collection = collect(['a', 'b', 'c']);
$upper = $collection->toUpper(); // ['A', 'B', 'C']
keyBy()
, groupBy()
, or where()
for better performance.Laravel Collections provide an elegant and efficient way to manipulate data. Whether you're filtering, sorting, transforming, or aggregating, Collections offer a clean and expressive syntax.
By mastering Collections, you can write more readable and maintainable Laravel code. Start applying these techniques in your projects today!
Happy coding! 🚀
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google