I have a GET
endpoint that accepts a boolean active
and an integer ID
as a query parameter. Something like GET /stuff?active=1&ID=10
.
Neither of these parameters are required.
If I were to do GET /stuff?active=1
and would try to retrieve the value from the Request
by doing $request->get('active')
I would get a value of 1
as a string.
If having declare(strict_types=1)
enabled and a method in a service such as
public function getBy(bool $active = null) {
...
}
And calling the method in a Controller
for example
$controllerMethod->getBy($request->get('active'))
would result in Argument #0 ($active) must be of type ?bool, string given
which is obviously not good.
Now my question: Is there a way to cast the request parameters prior to them reaching the Controller
? Perhaps in a FormRequest
class somehow?
I’m well aware I can do $request->has('active') ? $request->get('active') : null
in the Controller
but this is just extra clutter that I would like to move somewhere else.
5
Answers
1 way (getter)
2 way (override)
Use
mergeIfMissing
.You can create your own custom middleware and put the below inside it or call the below inside the Controller’s constructor(depending upon your design)
Well, we all agree that query params are string!
What you can do:
you can create a middleware for this and try overwriting the parameter:
Outsourcing that to a FormRequest class should be working with either:
or by doing the same even before validation inside:
Documentation