The magic of Laravel Macro and Mixins with Examples

tutspack laravel
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello artisans,

How are you doing? In this tutorial, I will discuss with you Laravel Macro Collection and Mixins. If you don’t know about this cool feature of laravel then you are in the right place. I will discuss everything in detail with an example. So here we go.

What is Laravel Macro?

In simple word, Laravel Macro is a way to add some missing or extra functionality to Laravel’s internal component with a piece of code which doesn’t exist in the Laravel class. To implement a Laravel MacroLaravel provides a PHP trait called Macroable.

Macroable Laravel’s Classes

The following Laravel’s classes allow for macros to be created by using the Illuminate\Support\Traits\Macroable trait. Here are some of the most commonly used classes to create macros.

  1. Request: Illuminate\Http\Request
  2. Response: Illuminate\Http\Response
  3. Collection: Illuminate\Support\Collection
  4. Str: Illuminate\Support\Str
  5. Router: Illuminate\Routing\Router
  6. UrlGenerator: Illuminate\Routing\UrlGenerator
  7. Cache: Illuminate\Cache\Repository
  8. Filesystem: Illuminate\Filesystem\Filesystem
  9. Arr: Illuminate\Support\Arr
  10. Rule: Illuminate\Validation\Rule

There other classes and facades which use the Macroable trait. You can find all the classes and facades in the codebase of Laravel.

Let’s see an example of Laravel Macro.

To define a macro you can choose two options. If you want just two or three macro functions, then you can define inside the boot function App/Http/Providers/AppServiceProvider or make a dedicated service provider for macros. In this example, I will add a new couple of methods in Arr: Illuminate\Support\Arr and Str: Illuminate\Support\Str facades.

App\Providers\AppServiceProvider.php

//example 1 
Str::macro('grettings', function (string $userName) {
            return 'Hello ' . $userName;
        });

//example 2
Arr::macro('multiplyWith', function ($arr, $n) {
      return collect($arr)->map(function ($a) use ($n) {
             return $a * $n;
        });
   });

In the first example, I have defined a simple macro function which is concatenation user name with “Hello” text. I know, definitely, you don’t like this function in your application. You can define your own logic whatever do you want.

Well, The second macro function I have defined that which is receive an array and a number then return an array which is multiply with the number.

Well, Now arise a question, How to you use this macros ?

As it is ,we use facades helper we can use macros function. I have define a route for example purpose you can use in your controller or others.

routes/web.php

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
Route::get('macro', function () {
    return Arr::multiplyWithN([10, 20, 30], 2); //[20,40,60]
    return Str::grettings(Shahin); // Hello Shahin
});

Now I will show you how to use macros via mixins

Well, Mixinis is nothing but simple a class.If you have lot of macros on a specific facades then you can create a dedicated file for those functions.

Well, I have created a PHP class file in App/Mixins folder ArrayMixin.php

<?php

namespace App\Mixins;

use Illuminate\Support\Arr;

class ArrayMixin
{
    public function multiplyWithN()
    {
        return function ($arr, $n) {
            return collect($arr)->map(function ($a) use ($n) {
                return $a * $n;
            });
        };
    }
  public function OtherFunction()
    {
        return function () {
            return 10;
            });
        };
    }
}

In this file, I have created two methods you can create whatever you want. It’s up to you. Well, then you have to register this file in AppServiceProvider.

 public function boot(){
       Arr::mixin(new ArrayMixin);
   }

then you can use those macros as usual facades methods.

Hope It will help You.

Read More : Load more Data in Laravel using Ajax/Axios


Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

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