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

April 21, 2018 —John Koster

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.

#Signature

The signature of the hasMacro method is:

1public static function hasMacro(
2 $name
3);

#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;
2 
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;
2 
3Str::macro('soundex', function ($value) {
4 return soundex($value);
5});
6 
7// Would return true.
8Str::hasMacro('soundex');

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.