What are Laravel Macros and How to Extending Laravel’s Core Classes using Macros with example?

Harish Kumar · · 10931 Views

Laravel Macros are a great way of expanding Laravel's core macroable classes and add additional functionality needed for your application. In simple word, Laravel Macro is an approach to add some missing functionality to Laravel's core component with a piece of code which doesn't exist in the Laravel class. To implement a Laravel Macro, Laravel gives a PHP trait called Macroable. You can check Illuminate\Http\Response class of Laravel, which implements the Macroable trait, which implies you can extend the Illuminate\Http\Response class using a macro static method.

Registering a new macro

All macros should be registered inside the boot method in the service provider. You can create a dedicated service provider for macros, or you can add macros in the AppServiceProvider, shipped with the default Laravel installation. That is totally up to you.

Using anonymous function

This approach is a straightforward approach to add a new macro is putting it just inside the boot method for AppServiceProvider.

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Collection::macro('name it here', function(){
            // Pass your actual code here.
        });
    }
}

And you are done.

Here is an example of toUpper macro:

use Illuminate\Support\Str;

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

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

// ['FIRST', 'SECOND']

Using mixins

If you want to use lots of macros from a particular Laravel class. For this situation, your boot method of service provider most likely gets bigger with various macros, and the code begins looking messy.

To isolate your code, you can utilize mixins.

For this approach, you should utilize a mixin static method on the macroable class, and pass your mixin class as an argument.

Let's take a look at an example. Let's say, we have a Macros/QueryBuilderMacros.php file with the following content.

class QueryBuilderMacros
{
    public function one()
    {
        // macro content
    }

    protected function two()
    {
        // macro content
    }

    private function three()
    {
        // will not become a macro
    }
}

The following code is the example of mixin to register QueryBuilderMacros class with its methods.

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Builder::mixin(new QueryBuilderMacros());
    }
}

That is it. Methods of QueryBuilderMacros class, one and two will become available on each Builder class instance. Method three declared as private, will remain accessible just for methods in QueryBuilderMacros class, you know since private should remain private.

Conclusion

Laravel's macros are a compelling component, which opens a lot of conceivable outcomes to expand the Laravel framework, and helps to get rid of repeating the same logic across the application.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

Part #1: Closure-based Custom Laravel Validation

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar

Mobile App Development Process

With businesses adopting a mobile-first approach and the growing number of mobile apps, successful mobile app development seems like a quest. But it’s the process that determines (...)
Narola Infotech

Install Laravel Valet Linux+ development environment on Ubuntu System

The official Laravel Valet development environment is great if you are an Apple user. But there is no official Valet for Linux or Window system.
Harish Kumar