I am sending Query Params in Postman to a GET route.
The first parameter is sortByLocation which is a boolean value:
Of course I want to get it as boolean at backend.
I have a Form Request class named GetActivitiesRequest and one rule is:
'sortByLocation' => 'nullable|boolean',
When I send the request on Postman, I get the error:
{
"message": "The sort by location field must be true or false.",
"errors": {
"sortByLocation": [
"The sort by location field must be true or false."
]
}
}
So, the question is obvious, how can I get query params in their original types?
2
Answers
The issue you are having is related to the query parameters. In Laravel query parameters are always received as strings. So when you are passing ‘true’ or ‘false’ as query parameters, its rendered as string ‘"true"’ or ‘"false"’ not as a boolean value.
to handle this, you can modify ‘GetActivitiesRequest’ class to convert the ‘sortByLocation’ query parameter to a boolean value before validation.
Here is a sample code.
this will convert the boolean value before validation, so the ‘boolean’ rule will pass.
Use the
boolean
method. For an example :Here is the link for official documentation.
$request->boolean()
is the same thing for what @vijay-panwar suggested.Check this out if you are curious – src/Illuminate/Http/Concerns/InteractsWithInput.php
Quick note that you could pass 1 (as true) or 0 (as false) for boolean values in the query parameters.