The Laravel Framework is the most eloquent, strong, magical and beautiful framework ever made. You are being amazed continuously when you deep drive into this framework because of its beauty, extendibility and code art. In this article, I am going to introduce another cool feature of Laravel, which is Macro. It gives you more flexibility to extend the Laravel core classes! You can do more stuff by a macro feature which is not offered by Laravel by default! Most of the Laravel core classes are macroable, which I'll list out at the end of this article.
Let's talk about a real-life example, When we make RESTful API, we need to give the response in a standard JSON format. Typically we give a response of our API like.
// for success
return response()->json(['success' => true,'message' => 'Successful']);
//for fail
return response()->json(['success' => false,'message' => 'Failed']);
What if response class has a success method, that will be great and we don't have to same code again and again. To do that, we can create our macros. Let's do that. We need to make our own macro in the boot method of AppServiceProvider.php
//app/Providers/AppServiceProvider.php
public function boot()
{
Response::macro('success', function ($message) {
return ['success' => true,'message' => $message];
});
Response::macro('fail', function ($message) {
return ['success' => false,'message' => $message];
});
}
Done! now we can use success
and fail
method from Laravel core Response class in our entire application like below.
Success response
return response()->success('Successful');
Output
{
"success": true,
"message": "Successful"
}
Fail response
return response()->fail('Failed!');
Output
{
"success": true,
"message": "Failed!"
}
If we need more macros then the boot method will be bigger and bigger. In this situation, we can use mixings in app/Mixins
namespace App\Mixins;
use Illuminate\Support\Facades\Response;
class ReponseMixin
{
Response::macro('success', function ($message) {
return ['success' => true,'message' => $message];
});
Response::macro('fail', function ($message) {
return ['success' => false,'message' => $message];
});
Response::macro('data', function ($data) {
return ['success' => false,'data' => $data];
});
}
now in the boot method, we can simply register our mixins.
//app/Providers/AppServiceProvider.php
public function boot()
{
Response::mixin(new ReponseMixin);
}
You can make your own macro with these Laravel core classes.
Hope this article will help you understand Laravel macro features and learnt how you can make your own Laravel macro by extending the Laravel core classes. If this article helpful to you then please share this with others.