Laravel 5

Laravel 5 Macros: Defining a Callback Function Macro With macro


John Koster

Published on April 21, 2018

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


The signature of the macro method is:

1public static function macro(
2 $name,
3 $macro

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;
3Str::macro('chunk', function ($value, $length) {
4 return collect(str_split($value, $length));

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';
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.