Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel Macros: Extend Framework Features

Add custom methods to Laravel classes using macros.

16 January 20261 min readLaravelاقرأ بالعربية

On this page

  1. Response Macro
  2. Collection Macro
  3. Builder Macro
  4. Usage

Extend Laravel with macros:

Response Macro

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

Collection Macro

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

Builder Macro

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

Usage

php
return response()->success($data);
$items->toUpper();
User::whereLike('name', 'john')->get();
All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read