Posts tagged with collections

Join 9,500+ smart developers

Every month I share what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Creating strictly typed arrays and collections in PHP

You might thing that PHP is not able to automatically perform a type check on items in an array. But using variadic constructor this is possible. Bert Ramakers wrote a blogpost with some good examples on how to do this.

One of the language features announced back in PHP 5.6 was the addition of the “…” token to denote that a function or method accepts a variable length of arguments.

Something I rarely see mentioned is that it’s possible to combine this feature with type hints to essentially create typed arrays.

https://medium.com/2dotstwice-connecting-the-dots/creating-strictly-typed-arrays-and-collections-in-php-37036718c921

Read more

Understanding Laravel’s HighOrder Collections

One of my favourite features that was introduced in Laravel 5.4 are the higher order collection functions. It allows you to rewrite

collect($models)->filter(function(Model $model) {
   $model->passesFilter();
});

to:

collect($models)->filter->passesFilter();

This works with the filter method an a bunch of other collection methods.

In a new post on his blog Nicola Malizia explains how these methods work under the hood.

A new version of Laravel is available from 24 January 2017 and, as usual, it comes with a lot of new features. Among them, there is one that takes advantage of the dynamic nature of PHP. Some out of there will contempt this, but I find it awesome!

https://unnikked.ga/understanding-laravels-highorder-collections-ee4f65a3029e

Read more

How I refactor to collections

Christopher Rumpel posted some good practical examples on how to refactor common loops to collections.

Refactoring to Collections is a great book by Adam Wathan where he demonstrates, how you can avoid loops by using collections. It sounds great from the beginning, but you need to practice it, in order to be able to use it in your own projects. This is why I refactored some of my older projects. I want to share these examples today with you.

http://christoph-rumpel.com/2016/11/How-I-refactor-to-collections/

Read more

Debugging collection chains original

by Freek Van der Herten – 2 minute read

A couple of weeks ago I published a blog post on how you can easily debug collections using a dd macro. Meanwhile my company released a package that contains that macro. In this post I'd like to introduce a new dump macro, recently introduced in the package, that makes debugging collection chain…

Read more

Some handy collection macros original

by Freek Van der Herten – 4 minute read

Laravel's collection class is truly wonderful. It contains a lot of handy methods and you can create some very elegant code with it. In client projects I found myself adding the same macro's over and over again. That's why my colleague Seb and I took some time to create a package aptly called…

Read more

Debugging collections original

by Freek Van der Herten – 3 minute read

Lately I've been working a lot with collections in Laravel. If you're not in the know: a collection is a sort of super charged array with a lot of powerful functions to transform the data inside it. The only thing I found a bit of a hassle is how to debug the various steps in a collection chain.…

Read more

The pipe collection macro original

by Freek Van der Herten – 2 minute read

A few days ago I blogged some code to fetch data from Packagist using our homebrew wrapper around the packagist API. To summarize the amount of downloads this code was used: $totals = collect($packagist->getPackagesByVendor('spatie')['packageNames']) ->map(function…

Read more

Getting package statistics from Packagist original

by Freek Van der Herten – 2 minute read

At my work I'm currently creating a new dashboard. That's a fancy term for an html page sprinkled with some Vue magic that will be displayed on tv screen at the wall of our office. I won't say much about the dashboard itself on this post, but I'll make sure to write something on that in the near…

Read more

Cleaning Up Form Input with Transpose

Adam Wathan has another excellent article on using collections. This time he tackles the less used transpose-function.

Transpose is an often overlooked list operation that I first noticed in Ruby.

The goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.

http://adamwathan.me/2016/04/06/cleaning-up-form-input-with-transpose/

Personally, I can't wait until the release of his book: Refactoring To Collections.

Read more

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
function4(function3(function2(function1(collect(['jack','cheats'])))));

//lots of macros
collect(['i', 'want', 'to', 'live', 'in', 'a', 'desert'])
  ->function1()
  ->function2()
  ->function3()
  ->function4();

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.

Read more