I am sending a post request using postman to my Laravel API.
{
"title" : "abc",
"body" : [
{"type":"paragraph","data":{"text":"aSADAd"}},
{"type":"header","data":{"text":"Heading......","level":2}},
{"type":"paragraph","data":{"text":"This is a para"}},
{"type":"list","data":{"style":"ordered","items":["ABC","XYZ"]}}
],
"status" : 1
}
The body field is a JSON data field - the JSON.stringify output from the editor js.
My laravel validation rules are -
$validator = Validator::make($request->all(), [
'title' => 'required|string|max:255',
'body' => 'required|json',
'status' => 'required|boolean'
]);
But I m getting this error -
{
"validation_error": {
"body": [
"The body must be a valid JSON string."
]
}
}
try array
$validator = Validator::make($request->all(), [
'title' => 'required|string|max:255',
'body' => 'required|array',
'status' => 'required|boolean'
]);
this will work if you set your model
/**
* The attributes that has json type.
*
* @var array
*/
protected $casts = [
'body' => 'array'
];
like this you can work with json mysql in laravel
NOTE : The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:
https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting
https://laraveldaily.com/working-with-mysql-json-columns-in-laravel-custom-properties-example/