What is the Macroable trait in Laravel?
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.