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 FreeMacro
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 AppServiceProvider
class’s boot()
method.
x
public function boot()
{
Str::macro('isLength', function ($str, $length) {
return static::length($str) == $length;
});
}
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.
xxxxxxxxxx
use Illuminate\Support\Str;
dd(Str::isLength('This is a Laravel Macro', 23)); // true
Laravel’s Macroable Classes
The following list are all of the Laravel classes that currently use the Macroable
trait and accept macro calls.
- Illuminate\Auth\RequestGuard
- Illuminate\Auth\SessionGuard
- Illuminate\Cache\Repository
- Illuminate\Console\Command
- Illuminate\Console\Scheduling\Event
- Illuminate\Cookie\CookieJar
- Illuminate\Database\Eloquent\FactoryBuilder
- Illuminate\Database\Eloquent\Relations\Relation
- Illuminate\Database\Grammar
- Illuminate\Database\Query\Builder
- Illuminate\Database\Schema\Blueprint
- Illuminate\Filesystem\Filesystem
- Illuminate\Foundation\Testing\TestResponse
- Illuminate\Http\JsonResponse
- Illuminate\Http\RedirectResponse
- Illuminate\Http\Request
- Illuminate\Http\Response
- Illuminate\Http\UploadedFile
- Illuminate\Mail\Mailer
- Illuminate\Routing\PendingResourceRegistration
- Illuminate\Routing\Redirector
- Illuminate\Routing\ResponseFactory
- Illuminate\Routing\Route
- Illuminate\Routing\Router
- Illuminate\Routing\UrlGenerator
- Illuminate\Support\Arr
- Illuminate\Support\Collection
- Illuminate\Support\LazyCollection
- Illuminate\Support\Str
- Illuminate\Support\Testing\Fakes\NotificationFake
- Illuminate\Translation\Translator
- Illuminate\Validation\Rule
- Illuminate\View\Factory
- Illuminate\View\View
Published at DZone with permission of Razet Jain. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments