What is the Macroable trait?
TheMacroable trait lets you attach new methods to a class at runtime without modifying the class itself. Many of Laravel’s core classes use this trait, so you can extend them freely without forking or overriding core code.
The implementation lives in Illuminate\Support\Traits\Macroable. Registered macros are stored in the static $macros property and invoked through the __call / __callStatic magic methods.
Classes that support macros
macro() — adding a method
Pass the method name as the first argument and a closure as the second.$this is bound to the instance that called the macro, giving you direct access to the class’s properties and methods.
mixin() — registering multiple methods at once
When you have many macros to register, group them in a mixin class. Allpublic and protected methods of the mixin are registered as macros.
Each method in a mixin class must return a closure. The closure is the actual macro implementation.
Registering macros in a service provider
Macros must be registered before any code uses them. Theboot() method of AppServiceProvider is the right place.
Practical use cases
Extending Collection
Adding custom methods to collections is the most common use of macros.Extending Str
Extending Request
Extending Blueprint (migrations)
Grouping common column patterns into a macro keeps your schema definitions consistent.Extending TestResponse
Add custom assertion methods to clean up your tests.hasMacro() — checking whether a macro exists
flushMacros() — removing all macros
Use this in tests when you need a clean slate between test cases.Static macros
Macros work as static method calls in addition to instance calls. The__callStatic magic method handles this.
Adding Macroable to your own classes
You can include theMacroable trait in any class you write.
How it works internally
Closure::bindTo(), which makes $this refer to the object that called the macro. Non-closure callables (invokable objects) are not bound.
Next steps
The Pipeline pattern
Learn how to compose sequential processing steps with the Pipeline pattern.