php - Laravel validation: Must be a valid JSON string with the "json" rule
Solution:
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"
]);
Answer
Solution:
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.
Answer
Solution:
laravel have a convenient way to validate a request please follow these steps to make your own request and response for api
1-php artisan make:request YourRequest
Then customize your request like this
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Response;
class OrderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
$rules = [
'your filed name' => 'required',
];
return $rules;
}
/**
* Get the error messages that apply to the request parameters.
*
* @return array
*/
public function messages()
{
return [
'your field name' => 'custom message',
];
}
/**
* Handle a failed validation attempt.
*
* @param Validator $validator
* @return void
*
* @throws ValidationException
*/
protected function failedValidation(Validator $validator)
{
$error = collect($validator->errors())->collapse()->toArray();
$errors = implode(' | ', $error);
throw new HttpResponseException(response()->json(
['response' => ['status' => false, 'message' => $errors]],
Response::HTTP_UNPROCESSABLE_ENTITY));
}
}
this will solve error as recommended by laravel and its a professional way
then use this Request into controller .
if you want to use your own code then
just use json_encode($this->text_sizes)