Skip to main content

What is the Macroable trait?

The Macroable 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.
Inside the closure, $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. All public 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. The boot() 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.
flushMacros() removes every macro registered on that class. If you call it in tearDown(), macros registered by other tests or service providers will also be removed.

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 the Macroable trait in any class you write.

How it works internally

Closures are bound using Closure::bindTo(), which makes $this refer to the object that called the macro. Non-closure callables (invokable objects) are not bound.
For IDE auto-completion, annotate your macros with @method docblocks, or use the Laravel IDE Helper package to auto-generate helper files.

Next steps

The Pipeline pattern

Learn how to compose sequential processing steps with the Pipeline pattern.
Last modified on July 13, 2026