Laravel 12 Macros: A Complete Guide

5 min readUpdated on

Macros let you add your own methods to Laravel’s core classes without touching the framework’s source code. Below: how to register them in Laravel 12 and the kinds you will actually use.

What Are Macros?

Macros use PHP’s magic __call method to add custom methods to classes that use the Macroable trait.

Creating Basic Macros

The most common place to register macros is in a service provider’s boot method. Let’s start with a simple example:

php
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Str::macro('toSnakeCase', function (string $value) {
            return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $value));
        });
    }
}

Now you can use this macro anywhere in your application:

php
echo Str::toSnakeCase('HelloWorld'); // outputs: hello_world

Types of Macros

Most of Laravel’s core classes use Macroable. These are the ones I reach for:

Response Macros

Response macros give you a reusable response format:

php
use Illuminate\Support\Facades\Response;

Response::macro('success', function ($data, $message = 'Success') {
    return Response::json([
        'success' => true,
        'message' => $message,
        'data' => $data,
    ]);
});

Response::macro('error', function ($message, $code = 400) {
    return Response::json([
        'success' => false,
        'message' => $message,
    ], $code);
});

Usage in controllers:

php
public function index()
{
    $users = User::all();
    return response()->success($users, 'Users retrieved successfully');
}

public function show($id)
{
    $user = User::find($id);
    
    if (!$user) {
        return response()->error('User not found', 404);
    }
    
    return response()->success($user);
}

Collection Macros

Collection macros add your own data manipulation methods:

php
use Illuminate\Support\Collection;

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return strtoupper($value);
    });
});

Collection::macro('filterByStatus', function ($status) {
    return $this->filter(function ($item) use ($status) {
        return $item->status === $status;
    });
});

Using collection macros:

php
$collection = collect(['hello', 'world']);
$result = $collection->toUpper(); // ['HELLO', 'WORLD']

$users = User::all()->filterByStatus('active');

Request Macros

Request macros add custom data retrieval or validation helpers. Laravel already ships validate() and hasAny() on the request, so these use new names:

php
use Illuminate\Support\Facades\Request;

Request::macro('ids', function (string $key = 'ids'): array {
    return array_map('intval', array_filter((array) $this->input($key)));
});

Request::macro('validateOrNull', function (array $rules): ?array {
    $validator = validator($this->all(), $rules);

    return $validator->fails() ? null : $validator->validated();
});

Query Builder Macros

Extend the query builder with custom query methods:

php
use Illuminate\Database\Query\Builder;

Builder::macro('whereContains', function ($column, $value) {
    return $this->where($column, 'LIKE', "%{$value}%");
});

Builder::macro('whereStatus', function ($status) {
    return $this->where('status', $status);
});

Usage:

php
$users = DB::table('users')->whereContains('name', 'John')->get();
$activeUsers = DB::table('users')->whereStatus('active')->get();

Eloquent Builder Macros

Similar to query builder macros, but specifically for Eloquent:

php
use Illuminate\Database\Eloquent\Builder;

Builder::macro('active', function () {
    return $this->where('status', 'active');
});

Builder::macro('recent', function ($days = 7) {
    return $this->where('created_at', '>=', now()->subDays($days));
});

Using Eloquent macros:

php
$activeUsers = User::active()->get();
$recentPosts = Post::recent(14)->get();

String Macros

Extend the Str helper with custom string manipulation methods:

php
use Illuminate\Support\Str;

Str::macro('prefix', function ($string, $prefix) {
    return $prefix . $string;
});

Str::macro('surround', function ($string, $wrapper = '"') {
    return $wrapper . $string . $wrapper;
});
php
echo Str::prefix('world', 'hello '); // hello world
echo Str::surround('quoted'); // "quoted"

Advanced Macro Techniques

Macros with Multiple Parameters

A macro is a closure, so it takes any parameters you like:

php
Collection::macro('groupByMultiple', function (array $keys) {
    return $this->groupBy(function ($item) use ($keys) {
        return implode('-', array_map(fn($key) => $item[$key], $keys));
    });
});

Macros that Return the Instance

For chainable macros, return $this:

php
Collection::macro('debug', function () {
    dump($this->toArray());
    return $this;
});

// Usage
collect([1, 2, 3])
    ->debug()
    ->map(fn($n) => $n * 2)
    ->debug();

Mixin Classes

For organizing multiple related macros, use mixin classes:

php
namespace App\Mixins;

class ResponseMixin
{
    public function success()
    {
        return function ($data, $message = 'Success') {
            return response()->json([
                'success' => true,
                'message' => $message,
                'data' => $data,
            ]);
        };
    }

    public function error()
    {
        return function ($message, $code = 400) {
            return response()->json([
                'success' => false,
                'message' => $message,
            ], $code);
        };
    }
}

Register the mixin in your service provider:

php
use Illuminate\Support\Facades\Response;
use App\Mixins\ResponseMixin;

public function boot(): void
{
    Response::mixin(new ResponseMixin());
}

Best Practices

  1. Organize Your Macros: Register different types of macros in dedicated service providers.
  2. Document Your Macros: Add PHPDoc comments so IDEs know your methods:
php
/**
 * @method \Illuminate\Support\Collection toUpper()
 * @method \Illuminate\Support\Collection filterByStatus(string $status)
 */
  1. Use Mixins for Related Functionality: Group related macros into one mixin class.
  2. Test Your Macros: Unit-test them like any other code:
php
public function test_to_upper_macro()
{
    $collection = collect(['hello', 'world']);
    $result = $collection->toUpper();
    
    $this->assertEquals(['HELLO', 'WORLD'], $result->toArray());
}
  1. Avoid Naming Conflicts: Do not reuse names of existing Laravel methods, or of methods a future version might add. A macro is only reached through __call, so a native method with the same name wins and your macro is silently ignored (this is why the examples above avoid whereLike, wrap, hasAny and validate, which all exist in Laravel).

Conclusion

Keep macros small, register them in a service provider, and give them names Laravel does not already use.

Related articles

Existing system support

Need help with a live application?

I help companies improve live systems, clean up delivery workflows, and ship new features without adding avoidable complexity.

Comments (0)
Sign in to leave a comment

You need to be signed in to add a comment.

Login

Need someone to take responsibility for the next step?

Let’s talk about your project and define a scope that actually makes sense for your goals.