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();
Link:
This post is submitted by our members. Submit a new post.
Tags: Tutorials Laravel 5 Laravel 5.1 Tips Tricks