#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.

1$ 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:

 1namespace App\Providers;
 3use Illuminate\Support\Str;
 4use Illuminate\Http\Request;
 5use Illuminate\Support\ServiceProvider;
 7class RequestServiceProvider extends ServiceProvider
 9    public function register()
10    {
11    }
13    public function boot()
14    {
15        Request::macro('listOfIntegers', function (string $key): array {
16            $input = $this->input($key); /* @phpstan-ignore-line */
17            if (is_string($input)) {
18                if (empty($input)) {
19                    return [];
20                }
21                $input = Str::of($input)->explode(',');
22            }
23            return collect($input)
24                ->map(fn ($entry) => (int) trim($entry))
25                ->toArray();
26        });
27    }

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:

2$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:

1$ php artisan ide-helper:generate