How to Create And Uses Laravel Macro Example

Macro is the powerful feature of the laravel framework. Macros allow you to add on custom functionality to internal Laravel components like response:: macro, laravel macroable etc. This laravel macro also work with laravel apps.

How to Create And Uses Laravel Macro Example

Let’s see the following example for create and use of laravel macro; as follows:

Example 1

Let’s say you are working with the api and want the below response on success

	"success": true,
	"msg": "Your message",
	"data": Array()

To achieve the above response. Open the AppServiceProvider.php file and put the below code

Request::macro(‘success’, function ($msg, $data) {
    	"success" => true,
    	"msg" => $msg,
    	"data" => $data

And then use the above defined method

Request::success('Your message', Array());

Example 2

Let’s see another example. Suppose you want to create a new method which we will use at the time of fail

Open the AppServiceProvider.php file and put the below code

Request::macro(‘fail’, function ($msg, $data) {
    	"success" => false,
    	"msg" => $msg,

And then use

Request::fail('Your message');

Will return

	"success": false,
	"msg": "Your message"

You can create another macro according to your requirement using laravel macro

Which components are “Macroable” in laravel?

Macros can be defined on any class with the Macroable trait. Below is a list of Macroable facades & classes:


  • Cache
  • File
  • Lang
  • Request
  • Response
  • Route
  • URL

Illuminate Classes

  • Illuminate\Routing\UrlGenerator
  • Illuminate\Cache\Repository
  • Illuminate\Validation\Rule
  • Illuminate\Console\Scheduling\Event
  • Illuminate\Database\Eloquent\Builder
  • Illuminate\Database\Eloquent\Relation
  • Illuminate\Database\Query\Builder
  • Illuminate\Filesystem\Filesystem
  • Illuminate\Foundation\Testing\TestResponse
  • Illuminate\Http\RedirectResponse
  • Illuminate\Http\Request
  • Illuminate\Http\UploadedFile
  • Illuminate\Routing\ResponseFactory
  • Illuminate\Routing\Router
  • Illuminate\Support\Str
  • Illuminate\Support\Arr
  • Illuminate\Translation\Translator
  • Illuminate\Support\Collection

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch


My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *