How to Create and Use Custom Laravel Macro

In Laravel, a macro is a way to extend the functionality of a particular class or object with new methods, without having to modify the underlying code.

Macros can be defined on many different classes in Laravel, including Eloquent models, database query builders, and more. 

Table of Contents

  1. Create a Macro
  2. Use the Macro
  3. Macroable Classes

Create a Macro

For example, let's say you want to add a new method to the Illuminate\Support\Collection class that returns the average value of the collection. You can define the macro in your AppServiceProvider class’s boot() method:

App\Providers\AppServiceProvider.php
use Illuminate\Support\Collection;

public function boot()
{
    Collection::macro('averageValue', function () {
        return $this->sum() / $this->count();
    });
}

Use the Macro

You can then use this method like any other method on a Collection object:

$collection = collect([1, 2, 3, 4, 5]);
$average = $collection->averageValue(); // returns 3

Macroable Classes

Before creating a Laravel Macro, you have to make sure your targeted class uses the Macroable trait. Please navigate the page to see all available macroable classes.

Overall, macros are a powerful tool in Laravel that allow you to add custom functionality to existing classes in a clean and organized way. 👍