我正在使用邮递员向我的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
}
body字段是JSON数据字段-编辑器js的JSON.stringify输出。
我的laravel验证规则是-
$validator = Validator::make($request->all(), [
'title' => 'required|string|max:255',
'body' => 'required|json',
'status' => 'required|boolean'
]);
但是我遇到了这个错误-
{
"validation_error": {
"body": [
"The body must be a valid JSON string."
]
}
}
答案 0 :(得分:1)
尝试array
$validator = Validator::make($request->all(), [
'title' => 'required|string|max:255',
'body' => 'required|array',
'status' => 'required|boolean'
]);
这将在您设置模型的情况下起作用
/**
* The attributes that has json type.
*
* @var array
*/
protected $casts = [
'body' => 'array'
];
像这样,您可以在laravel中使用json mysql
注意:数组转换类型在处理以序列化JSON存储的列时特别有用。例如,如果您的数据库具有包含序列化JSON的JSON或TEXT字段类型,则在Eloquent模型中访问该属性时,将数组强制转换为该属性将自动反序列化为PHP数组:
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/