We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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:
<?php
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
<?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
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.