Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Using collection macros in Laravel

Laravel 5.2 provides some nice additions to the framework. One handy feature that I don’t see listed in the release notes is that Collection now is macroable.  Using it’s macro function you can easily extend Illuminate\Support\Collection with your own custom functions.

Take a look at this piece of code to uppercase every string in a collection.

$uppercaseWords = collect(['code', 'ferengi'])->map(function($word)  {
   return strtoupper($word);

That’s good code, but image you need to uppercase a lot of collections. Typing the same closure will get very tiresome. Let’s improve this with a macro.

use Illuminate\Support\Collection;

Collection::macro('uppercase', function() {

    return collect($this->items)->map(function($word) {
        return strtoupper($word);


You could create a service provider to load up these macro’s. Now that the macro is defined let’s uppercase collections like there’s no tomorrow:

$uppercaseWords = collect(['code', 'ferengi'])->uppercase();
$moreUppercaseWords = collect(['love', 'the', 'facade'])->uppercase();
$evenMoreUppercaseWords = collect(['activerecord', 'forever'])->uppercase();

You could be thinking “Why should I use a macro? I can easily to this with a regular function.”. Consider this piece of code.

function uppercase($collection) {

$uppercaseWords = uppercase(collect(['halo','five']));

It works, but you have to encapsulate the collection with your function. The last executed function is put first, which is confusing. With macro’s you can still chain functions and greatly improve readability.

//lots of functions

//lots of macros
collect(['i', 'want', 'to', 'live', 'in', 'a', 'desert'])

Sure, the examples use in this post were a bit contrived, but I hope you see that collection macro’s can be very handy.

EDIT: it seems that collection macro’s were introduced in Laravel 5.1.25 a month ago.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • Nice article, Freek, but I think I would either leave out or explain more the “scalar type hinting and return types” code. Many (most?) devs are not really familiar with that yet & it makes it difficult to understand the main code example, which is the whole point of the article.

    • That’s a good point. But I’m hoping if those devs get exposed to the new syntax here and there, they’ll investigate it and pick it up.

      • From the point of view of a technical reviewer, I think they are more likely to just skip the article & not share it. Teach one thing at a time is the best rule. People don’t have unlimited time and shouldn’t have to go learn something else first just to understand what you are teaching.

        • You’re right, it looks better without the type hints. Removed them (there was also a big error in them (see previous comments)).

          • wonder if:

            $uppercaseWords = ([‘code’, ‘ferengi’])->uppercase();

            shouldn’t be:

            $uppercaseWords = collect([‘code’, ‘ferengi’])->uppercase();

          • yup :-/. That’ll teach me not just typing code in wordpress. Will copy paste from my ide in the future and scrutinize it a bit more.

          • We all do it 🙂

            Last comment – it was quietly merged into 5.1 right before 5.2 came out (don’t recall the patch number) so you might be better just saying 5.2 so folks don’t try it on an older install of 5.1 (or at least make them aware)

      • Joseph Silber

        But is that even correct? The closure returns a string, not a collection. It is map that returns the collection.

        • You’re right. Thanks for letting me know. Not sure how that error got up there. Removed the type hints altogether. Will write a seperate post about that (hopefully without errors :-))

  • Also having macros on collections means that you keep the collections themselves immutable, which is nice 🙂 Every time you call one of those methods, you’re dealing with a new collection instance after the fact.

  • Great.. so L5.1 able to use it too 🙂

  • jblyberg

    Nice! This is relevant to something I’m working on right now.