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

Harish Kumar · · 12769 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:

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar

PHP Generators: Efficient Data Handling and Iteration Techniques

PHP Generators offer a powerful and memory-efficient way to handle large datasets and complex iteration scenarios in your applications. They provide a more elegant solution compared (...)
Harish Kumar

Compress and Download Files in Laravel Using ZipArchive with Examples

In web development, file compression is essential for optimizing data transfer and storage. Laravel provides tools for creating and downloading compressed files. This guide explores (...)
Harish Kumar

Implementing Multi-Authentication with Guards in Laravel

This guide provides a detailed explanation of how to implement multi-authentication using guards in a Laravel application. This is useful for applications that need to support (...)
Harish Kumar