如何解决Laravel JSON验证因邮递员而失败
我正在使用邮递员向我的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."
]
}
}
解决方法
尝试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/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。