laravelquery-string

Laravel get method query paramteres are coming as string, I need them in their original data type such as boolean


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?


Solution

  • 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 App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    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.