
Using macros with Laravel
27 Nov 2021 #development #laravel #php
One of the nice things in Laravel is that you can extend pretty much any class with your own methods. On each class which has the trait Macroable
, you can define extra methods, also called "macros".
To get started, start with creating a new ServiceProvider
in which we will define the macros.
$ php artisan make:provider RequestServiceProvider
This will create the file app/Providers/RequestServiceProvider.php
.
Before you start adding any code to it, declare it as a service provider in your config/app.php
file under the key providers
.
Once that is done, we can start defining our macros in the boot
method of the service provider like this:
namespace App\Providers; use Illuminate\Support\Str;use Illuminate\Http\Request;use Illuminate\Support\ServiceProvider; class RequestServiceProvider extends ServiceProvider{ public function register() { } public function boot() { Request::macro('listOfIntegers', function (string $key): array { $input = $this->input($key); /* @phpstan-ignore-line */ if (is_string($input)) { if (empty($input)) { return []; } $input = Str::of($input)->explode(','); } return collect($input) ->map(fn ($entry) => (int) trim($entry)) ->toArray(); }); }}
Just for your information, this macro allows us to parse a list of integers from a query string in both of these forms:
-
https://host/path?ids=1,2,3
-
https://host/path?ids[]=1&ids[]=2&ids[]=3
Once the macro is defined, you can now simply call the macro as if it was defined as a function on the class:
<?php$ids = $request->listOfIntegers('ids');
If you want to get autocompletion working in your IDE, you might need to regenerate the IDE helper file after defining the macro:
$ php artisan ide-helper:generate