Laravel Macros: Create And Use Macro with Examples

Laravel Macros: Create And Use Macro with Examples

Laravel macros are the secret ingredient that transforms your development experience from ordinary to extraordinary. They are the artisanal strokes of code that extend the elegance of Laravel’s syntax and functionality, giving you the ability to craft tailored methods directly onto Laravel’s core classes.

In Laravel, macros allow you to add custom methods to classes like the Illuminate\Support\Str class or the Illuminate\Http\Response class. Macros provide a powerful way to extend Laravel’s core functionality without modifying the underlying framework code. In this tutorial, you will learn how to create and use Laravel macros effectively.

Macro is a 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 Use Macro in Laravel 10|9|8

Steps to create and use of laravel macro with examples; as follows:

  • Step 1: Create a New Macro
  • Step 2: Register the MacroServiceProvider
  • Step 3: Using the Macro
  • Step 4: Create Your Own Macros

Step 1: Create a New Macro

Let’s start by creating a custom macro for the Str class. This macro will generate a random emoji to be used in your application.

Open your terminal and navigate to your Laravel project directory. And execute the following command on terminal or cmd to generate a new macro service provider:

php artisan make:provider MacroServiceProvider

Once you have executed the above command, now Open the generated MacroServiceProvider.php file located in the app/Providers directory. Inside the boot method of the provider, add the following code to define your macro:

use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

public function boot()
{
    Str::macro('randomEmoji', function () {
        $emojis = ['😃', '🚀', '🎉', '🔥', '🌟'];
        return $emojis[array_rand($emojis)];
    });
}

Step 2: Register the MacroServiceProvider

Now that you have defined your macro, you need to register the MacroServiceProvider in Laravel.

So, Open the config/app.php file. In the providers array, add your MacroServiceProvider:

'providers' => [
    // Other providers...
    App\Providers\MacroServiceProvider::class,
],

Step 3: Using the Macro

With your macro registered, you can now use it in your application.

Open a controller, model, or any other class where you want to use the randomEmoji macro. At the top of the file, import the Str facade:

use Illuminate\Support\Str;

Now you can use the randomEmoji macro anywhere in your code:

$emoji = Str::randomEmoji();

Step 4: Create Your Own Macros

You can create macros for various classes throughout Laravel, such as the Response class, Eloquent models, and more. Here’s a basic example of creating a macro for the Illuminate\Http\Response class that sets a custom header:

Open your MacroServiceProvider.php file. Inside the boot method, add the following code:

use Illuminate\Http\Response;

public function boot()
{
    Response::macro('withCustomHeader', function ($headerName, $headerValue) {
        return $this->header($headerName, $headerValue);
    });
}

Now you can use the withCustomHeader macro on any Response instance:

return response('Hello, world!')->withCustomHeader('X-Custom-Header', 'HelloHeader');

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:

Facades

  • 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

Conclusion

Laravel macros provide an elegant way to extend Laravel’s core functionality with your own custom methods. By following this tutorial, you’ve learned how to create and use macros to add unique features to various classes in your Laravel application. Experiment with different macros to enhance your application’s capabilities while keeping your code clean and organized.

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. 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 *