Benjamin Crozat The web developer life

Laravel Collections: the 2022 quick wins guide

Benjamin Crozat Benjamin Crozat2 minutes read

Before you start reading this article, did you know 76 persons subscribed to my newsletter?

Join them and enjoy free content about the art of crafting websites!

Laravel Collections: the 2022 quick wins guide

Laravel Collections are a powerful tool for manipulating arrays. They wrap native PHP array functions and provide a fluent interface for working with them. They’re also immutable, meaning they do not modify the original array, but instead return a new collection with the changes applied.

By using collections, you’ll stop wondering about:

And finally, your code will be more readable and easier to maintain.

Table of contents

Transform arrays into collections

First, let’s remind everyone that arrays can be transformed into collections using the collect() helper function. It’s that simple.

use \Illuminate\Support\Collection;
 
$collection = collect(); // Empty collection.
$collection = collect([1, 2, 3]); // Collection from an array.
$collection = new Collection([1, 2, 3]); // Object-oriented style.

Get rid of your foreach loops

The most common use case for collections is to replace foreach loops.

use App\Models\Post;
 
$posts = Post::all();
 
foreach ($posts as $post) {
//
}

With collections, use the each() method:

use App\Models\Post;
 
Post::all()->each(function (Post $post) {
//
});

You don’t need temporary variables

It is common practice to use temporary variables to store the result of a loop. Even if this is perfectly fine, collections allow you to do better.

$foo = [];
 
foreach ($bar as $baz) {
if ($baz->something()) {
$foo[] = $baz;
}
}
 
return $foo;

Instead, use the filter method and return the filtered collection.

return $bar->filter(function ($baz) {
return $baz->something();
});

How cool is that?

Do basic maths with fewer lines of code

Collections provide a set of methods to perform everyday mathematical operations on arrays.

Here’s how it looks using native PHP arrays:

$numbers = [1, 2, 3, 4, 5];
 
$sum = 0;
 
foreach ($numbers as $number) {
$sum += $number;
}
 
// $sum is now 15.
collect([1, 2, 3, 4, 5])->sum(); // 15

Of course, you can do more than add numbers.

$numbers = collect([1, 2, 3, 4, 5]);
 
$numbers->average(); // 3
$numbers->min(); // 1
$numbers->max(); // 5

Higher order messages (aka, sorcery)

Higher order messages are shortcuts that will make your code even more concise. Let me show you by example.

Can you refactor this code to a collection first?

foreach (User::where('foo', 'bar')->get() as $user) {
$user->notify(new SomeNotification);
}

Here’s the result:

User::where('foo', 'bar')
->get()
->each(function (User $user) {
$user->notify(new SomeNotification)
});

But we can do better.

Using higher-order messages, we can remove the anonymous function and directly access each User model notify() method.

That’s what I was saying; it feels like sorcery!

User::where('foo,' 'bar')
->get()
->each
->notify(new SomeNotification);

dd() is built into collections

Instead of encapsulating your collection inside a dd() helper, you can call the dd() method that’s built-in collections.

// Before.
dd($collection->where('foo', 'bar'));
 
// After.
$collection->where('foo', 'bar')->dd();

Other posts to read

AI is a trending topic in the programming space. It enables developers to do incredible things, and many startups build products around it.

Laravel 10 will be released on February 7, 2023. Its development is still ongoing. Let's dive into every relevant new feature we know about already.

Hiring a good developer can be challenging. But if you follow these tips and you will be able to hire the right fit for your projects.

Learn why the "Using $this when not in object context" error happens, and let me show you the only way to fix.

Learning a framework can be overwhelming. Time and practice will make you a master. Here are some best practices to help you toward your goal.

Laravel Dropbox Driver is a new storage you can add to your Laravel application and use it for all sorts of things.

Learn why the "Invalid argument supplied for foreach()" warning happens, and let me show you multiple ways to fix it.

Migrations are essential in any Laravel app using a database. I will tell you what they are, why you should use them and how you can generate them.

Are you looking for the best web hosting for Laravel projects and all budgets? I've got you covered. Here are the best I found.

Whether PHP is dead or not is a matter of numbers, not opinions. I will provide you with essential statistics that will lead you to make better decisions.