php - 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/
推荐阅读
- c# - ASP.NET Core - 服务器按需停止和启动
- c# - 蓝牙设备(RFCOMM 协议 TDI)驱动程序在手动关闭蓝牙然后在 Windows 平板电脑上打开时显示错误
- amazon-web-services - 适用于 AWS 的 Cron - 每小时运行一次,周二 10:30 到 12:30 之间除外
- android - 如果接入点没有互联网连接,则无法 ping 网关
- python - 如何调试已安装的 Python 应用程序?
- sql - Create multiple rows for results in multiple days
- react-native - 如何从定制的 flatlist 组件访问 flatList 方法,例如 scrollToIndex?
- angular - Schematics 适用于原理图项目,但不适用于 Angular 项目
- angularjs - AngularJS 错误 [$injector:unpr] 未知提供者:在 IE11 中使用 Minified JS
- python - jupyter notebook:使用与常量函数参数交互