What is the Macroable trait in Laravel?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

The Macroable trait allows adding custom methods to classes at runtime without subclassing. Many core Laravel classes (Response, Request, Collection, Str, Arr, Builder) use the Macroable trait. Add a macro in a service provider: Collection::macro("sumField", function($field) { return $this->sum(fn($item) => $item[$field]); }). Now $collection->sumField("price") works everywhere. Str::macro("initials", fn($name) => collect(explode(" ", $name))->map(fn($w) => strtoupper($w[0]))->implode("")). Macro methods have access to $this (the object the macro is called on). The mixin() method adds all public methods of a class as macros at once. Macros are a powerful extension mechanism — packages like Spatie use them extensively to add methods to Laravel core classes without forking them.

Pro Tip

This topic has Laravel-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.