Laravel 5

Laravel 5 Macros: Determining if a Class Has a Macro Defined With hasMacro


John Koster

Published on April 21, 2018

The hasMacro method is used to determine if a given class has a macro with the name $macro defined. It returns true if the $macro is found, otherwise it returns false.


The signature of the hasMacro method is:

1public static function hasMacro(
2 $name

Example Use

With a fresh Laravel installation, the Illuminate\Support\Str class does not define a method named soundex; the Str class also does not contain a macro named soundex. We can use the hasMacro method to interrogate the Str class in order to programmatically determine if a macro with a particular name exists:

1use Illuminate\Support\Str;
3// Will return false.
4$containsMacro = Str::hasMacro('soundex');

We can implement the soundex macro method (by returning the results of a call to PHP's soundex function) and then reevaluate the return results of the hasMacro method:

1use Illuminate\Support\Str;
3Str::macro('soundex', function ($value) {
4 return soundex($value);
7// Would return true.