How Laravel Collections Made My Life Easier
Tahsin Abrar

Tahsin Abrar @tahsin000

Joined:
May 17, 2023

How Laravel Collections Made My Life Easier

Publish Date: May 24
0 0

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'];
});
Enter fullscreen mode Exit fullscreen mode

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),
        ]);
    });
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

With Collections:

$admins = collect($users)->where('role', 'admin');
Enter fullscreen mode Exit fullscreen mode

2. Need to get the total sales from an array of orders.

$total = collect($orders)->sum('amount');
Enter fullscreen mode Exit fullscreen mode

3. Want to paginate a collection manually for a custom API.

$page = 2;
$perPage = 10;

$paginated = collect($data)->forPage($page, $perPage);
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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'),
]);
Enter fullscreen mode Exit fullscreen mode

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.

Comments 0 total

    Add comment