Not long ago, I was working on a client project that had a tight deadline. Like many of us do in crunch time, I started writing basic PHP loops and conditionals just to get things done.
But then something happened.
A fellow developer on my team walked up and casually said,
“Why aren’t you using Laravel Collections?”
That moment changed my workflow forever.
The Grocery Store Problem
Let me tell you a simple story that will relate to almost every developer.
Imagine you’re managing a grocery delivery system. You have a list of grocery items, and you need to:
- Remove any out-of-stock items
- Sort the items by price
- Group them by category
- And finally, format them for display
Seems simple enough, right? But writing raw foreach
loops for each step is not only time-consuming but also hard to maintain.
Here’s what I used to write:
$filteredItems = [];
foreach ($items as $item) {
if ($item['in_stock']) {
$filteredItems[] = $item;
}
}
usort($filteredItems, function ($a, $b) {
return $a['price'] <=> $b['price'];
});
And that was just to filter and sort. I hadn’t even grouped or formatted anything yet.
Enter Laravel Collections
Collections make this kind of work elegant, readable, and chained.
Here’s the exact same functionality using Laravel Collections:
$displayItems = collect($items)
->filter(fn($item) => $item['in_stock'])
->sortBy('price')
->groupBy('category')
->map(function ($group) {
return $group->map(fn($item) => [
'name' => ucfirst($item['name']),
'price' => '$' . number_format($item['price'], 2),
]);
});
That’s it.
No manual looping. No nested conditionals. Just readable, functional-style code.
A Few More Real-Life Scenarios
1. You have a list of users, and you want only the admins.
Before Collections:
$admins = [];
foreach ($users as $user) {
if ($user->role === 'admin') {
$admins[] = $user;
}
}
With Collections:
$admins = collect($users)->where('role', 'admin');
2. Need to get the total sales from an array of orders.
$total = collect($orders)->sum('amount');
3. Want to paginate a collection manually for a custom API.
$page = 2;
$perPage = 10;
$paginated = collect($data)->forPage($page, $perPage);
4. Removing duplicates based on a single field
Imagine a user uploads a list of products, and some of them are accidentally duplicated by SKU.
$uniqueProducts = collect($products)->unique('sku');
5. Transforming Data for Frontend Consumption
You have a list of blog posts, and you only need title, slug, and formatted date.
$formatted = collect($posts)->map(fn($post) => [
'title' => $post->title,
'slug' => $post->slug,
'date' => $post->created_at->format('M d, Y'),
]);
Why I Recommend Using Collections
Here’s what I’ve learned after switching to Collections:
- Readable code: Your intentions are clear from the function names.
- Less code: No need for boilerplate loops or conditionals.
- Maintainable: Easy to debug, refactor, or expand.
- Built-in power: You’re leveraging Laravel’s core functionality, which is optimized and tested.