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:
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:
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:
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:
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:
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:
$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:
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:
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:
$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:
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:
$activeUsers = User::active()->get();
$recentPosts = Post::recent(14)->get();
String Macros
Extend the Str helper with custom string manipulation methods:
use Illuminate\Support\Str;
Str::macro('prefix', function ($string, $prefix) {
return $prefix . $string;
});
Str::macro('surround', function ($string, $wrapper = '"') {
return $wrapper . $string . $wrapper;
});
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:
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:
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:
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:
use Illuminate\Support\Facades\Response;
use App\Mixins\ResponseMixin;
public function boot(): void
{
Response::mixin(new ResponseMixin());
}
Best Practices
- Organize Your Macros: Register different types of macros in dedicated service providers.
- Document Your Macros: Add PHPDoc comments so IDEs know your methods:
/**
* @method \Illuminate\Support\Collection toUpper()
* @method \Illuminate\Support\Collection filterByStatus(string $status)
*/
- Use Mixins for Related Functionality: Group related macros into one mixin class.
- Test Your Macros: Unit-test them like any other code:
public function test_to_upper_macro()
{
$collection = collect(['hello', 'world']);
$result = $collection->toUpper();
$this->assertEquals(['HELLO', 'WORLD'], $result->toArray());
}
- 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 avoidwhereLike,wrap,hasAnyandvalidate, which all exist in Laravel).
Conclusion
Keep macros small, register them in a service provider, and give them names Laravel does not already use.