How to Use Laravel Macro With Example?
Laravel Macros gives you more flexibility to extend the public interface of the Laravel core macroable classes.
Join the DZone community and get the full member experience.Join For Free
Macro is a powerful feature of the Laravel framework. Laravel Macros allow you to add custom functionality to internal Laravel components.
In this post, we will be looking at how we can use Laravel Macros and which classes can be used to define Macros.
If you see the Laravel codebase, you'll find countless references to a trait called
Macroable. This trait allows you to extend the public interface of a class in real-time.
Creating a Laravel Macro
Before creating a Laravel Macro, you have to make sure your targeted class use the
Macroable trait. Here, we will be creating a Macro on the
Illuminate\Support\Str class, which will check the length of a given string named
isLength. You can define the macro in your
Within the boot method of
AppServiceProvider, we are defining a
isLength macro on
Str class which simply compare the length of first parameter with second one.
Now, you can use this Macro anywhere in your application.
Laravel’s Macroable Classes
The following list are all of the Laravel classes that currently use the
Macroable trait and accept macro calls.
Published at DZone with permission of Razet Jain. See the original article here.
Opinions expressed by DZone contributors are their own.