Laravel macros are powerful, but registering them often feels more manual than it should.
Usually, the flow looks like this:
• write a helper method,
• wrap it in a closure,
• register it in a service provider,
• repeat for every macroable class.
That works, but it adds boilerplate and spreads macro logic across multiple places.
I recently looked at theflowbyte/laravel-macro-attribute, a small package that lets you register Laravel macros with PHP 8 attributes instead. The idea is simple: put a #[Macro(...)] attribute on a static method, register the class once, and the package binds the method as a macro for the target class automatically.
The problem with traditional macro registration
Laravel’s macro system is great for extending existing classes like:
• Collection
• Request
• Str
• ResponseFactory
• and other macroable classes
But in real projects, macro registration tends to become messy:
• macros are declared far from where they are registered,
• service providers grow into glue code,
• related macros are harder to discover,
• renaming methods and keeping registrations in sync becomes annoying.
The bigger the codebase, the more this friction shows up.
What this package does
laravel-macro-attribute lets you define macros directly on static methods using a PHP 8 attribute:
#[Macro(targetClass: Request::class)]
public static function isCrawler(Request $request): bool
{
$userAgent = strtolower($request->header('User-Agent', ''));
return str_contains($userAgent, 'bot');
}
You can find installation instructions and full usage examples in the project repository:
Top comments (0)