
CEO Vortechron
Laravel magical macros
Laravel macros allow developers to add custom functionality to Laravel's
core classes or even their own classes. They are simple and easy to use, and
provide a way to extend Laravel's functionality without modifying the
underlying code.
Macros can be defined for a wide range of classes, including Eloquent
models, collections, and request and response classes. They are a powerful
tool that enables developers to write cleaner, more concise code.
Request::macro('hello', function ($name) {
echo 'Hello ' . $name;
});
Request::hello('World'); // outputs "Hello World"
A more practical example of a Request macro would be detecting the domain base name
Request::macro('baseDomain', function ($domain) {
return Str::is($domain . '.*', $this->root());
});
Request::baseDomain('facebook') // returns true for facebook.com
Request::baseDomain('dev') // returns true for dev.to
Defining macros for your Laravel application in a service provider is a good
practice. While the AppServiceProvider's boot()
method is a
great starting point, it can become cluttered over time. To avoid this, you
can create a MacrosServiceProvider and register it in the config/app.php
file. If your macros are related, you can group them into a separate service
provider, such as the TldAwareServiceProvider which houses TLD-related
macros.
Available class to define macros
- Illuminate\Cache\Repository
- 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\Routing\UrlGenerator
- Illuminate\Support\Arr
- Illuminate\Support\Collection
- Illuminate\Support\Str
- Illuminate\Translation\Translator
- Illuminate\Validation\Rule