Laravel 5 Macros: Defining a Callback Function Macro With macro

April 21, 2018 —John Koster

The macro method is used to add a callback function macro to any class that utilize the "Illuminate\Support\Traits\Macroable" trait.

#Signature

The signature of the macro method is:

1public static function macro(
2 $name,
3 $macro
4);

#Example Use

The following example demonstrates how to add a new method chunk to the "Illuminate\Support\Str" class. This new method will take an input string and return an instance of "Illuminate\Support\Collection containing the various chunks of the string of a certain length:

1use Illuminate\Support\Str;
2 
3Str::macro('chunk', function ($value, $length) {
4 return collect(str_split($value, $length));
5});

After our new macro method has been added to the Str class, we can invoke it like so:

1$input = 'Testing our newly added macro method';
2 
3$chunks = Str::chunk($input, 5);

After the above example has executed, the $chunks variable would contain a collection containing eight elements containing the various pieces of our input string.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.