Back to articles
Clean Laravel Macros with PHP Attributes

Clean Laravel Macros with PHP Attributes

via Dev.to WebdevExa Byte

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

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
3 views

Related Articles