skip to Main Content

I am sending Query Params in Postman to a GET route.

The first parameter is sortByLocation which is a boolean value:

enter image description here

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


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

    namespace AppHttpRequests;
    
    use IlluminateFoundationHttpFormRequest;
    
    class GetActivitiesRequest extends FormRequest
    {
        /**
         * Prepare the data for validation.
         *
         * @return void
         */
        protected function prepareForValidation()
        {
            $this->merge([
                'sortByLocation' => filter_var($this->input('sortByLocation'), FILTER_VALIDATE_BOOLEAN),
            ]);
        }
    
        public function rules()
        {
            return [
                'sortByLocation' => 'nullable|boolean',
            ];
        }
    }
    

    this will convert the boolean value before validation, so the ‘boolean’ rule will pass.

    Login or Signup to reply.
  2. Use the boolean method. For an example :

    $sortByLocation = $request->boolean('sortByLocation');
    

    Here is the link for official documentation.

    $request->boolean() is the same thing for what @vijay-panwar suggested.

    public function boolean($key = null, $default = false)
    {
        return filter_var($this->input($key, $default), FILTER_VALIDATE_BOOLEAN);
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search