Benjamin Crozat The web developer life

Laravel Collections: the 2022 quick wins guide

Benjamin Crozat's avatar. Benjamin Crozat2 minutes read

Before you start reading this article, did you know 66 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();

I share everything I learn about the art of crafting websites, for free!

Other posts to read

Choose your web hosting provider and deploy your next Laravel project quickly and without any DevOps cost.

Take your code to the next level, thanks to exceptions. Handle errors in a more graceful way within try and catch blocks.

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

There are multiple ways to check if an array is empty. Let me tell you about each of them and why and when you should use them.

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

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.

Here are the best GDPR-compliant Google Analytics alternatives to help you avoid the GDPR penalty and keep your users safe.

Redirects in PHP are simple. I will guide you step by step and show you how to dodge some traps. Finally, we'll learn the nuance between 301 and 302 redirects.

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.

switch, case, and break. What are all these? When should you use it instead of if? What are its pros and cons?