What are macros in Laravel?

October 26, 2018

Macros are a quite clever, but simple way to add methods to existing classes. Many of Laravel's built in classes, such as the Request facade, can have user defined macros added. Let me explain by a simple example.

To enable macros, you just have to add use \Illuminate\Support\Traits\Macroable; in the class to use the Macroable trait. You can add it to any class. Many of the built in classes that come with Laravel will already use this trait.

A simple example to explain and show how to use macros in Laravel

I think a simple example from scratch should explain things quickly:
class SomeClass
    use \Illuminate\Support\Traits\Macroable;
    protected $some_var='aaaaa';
SomeClass::macro("getSomeVar",function() {
    return $this->some_var;
$a = new SomeClass;

Obviously, without the macro, there would be no way from anything outside of the class itself to access the $some_var property. But after adding the getSomeVar macro, you can access it.

This isn't a particularly useful macro - but it serves the point of showing how macros are set and how to use them.

A more real world example of using macros in Laravel

Here is an example that might be more useful in the real world.

Let's say you often want to return the first word, of the first element in a Collection object. This is trivial to do without a macro, but maybe you do it often enough that it makes sense to write a macro.

// add the macro
\Illuminate\Database\Eloquent\Collection::macro("firstWordOfFirstElement",function() {
    return explode(" ",$this->first())[0];
// create a collection:
$collection = collect("Apples are fruits","Computers are not food","Bananas are also fruits");
// and use the macro...
dd($collection->firstWordOfFirstElement()); //returns Apples

You would add the Request::macro(...) code in somewhere like your AppServiceProvider file.