I'm making a Laravel API, but I can't seem to send JSON data in one of the posts. I checked the other posts in StackOverflow, but it seems that my JSON request is correct, so I can't seem to find the error:
Here is the code in my Controller's method:
$validator = Validator::make($request->all(), [
"name" => "required|string",
"colors" => "json",
"sizes" => "json"
]);
if($validator->fails())
return response()->json(["errors" => $validator->errors()], 400);
Here is the request body:
{
"name": "Test",
"colors": {
"Man": "#0000ff",
"Second": "#FF0000"
},
"sizes": {
"titles": "20px"
}
}
The error:
{
"errors": {
"colors": ["The colors must be a valid JSON string."],
"text_sizes": ["The text sizes must be a valid JSON string."]
}
}
What seems to be the problem? Thank you!
Well you need to pass an JSON String instead of an JSON Object. This can be done either by json_encode
or JSON.stringify
.
As an answer on your last comment.:
You could either do this in your frontend application with JSON.stringify
or you could implement an Form Request with an prepareForValidation()
: https://laravel.com/docs/8.x/validation#prepare-input-for-validation.
Where you would do an json_encode()
on the json properties. Like:
protected function prepareForValidation()
{
$this->merge([
'colors' => json_encode($this->colors),
'text_sizes' => json_encode($this->text_sizes)
]);
}
Or in your case:
$validator = Validator::make($request->merge([
'colors' => json_encode($request->colors),
'text_sizes' => json_encode($request->text_sizes)
]), [
"name" => "required|string",
"colors" => "json",
"sizes" => "json"
]);
I found a simple solution, just use double quotes to represent a json string, and escape the double quotes inside the json:
{ "name": "Test", "colors": "{\"Man\": \"#0000ff\",\"Second\": \"#FF0000\"}", "sizes": "{\"titles\": \"20px\"}" }
This solve my issue sending json string from Insomnia Api rest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With