Laravel JSON 邮递员验证失败
Laravel JSON validation failed with postman
我正在使用 postman 向我的 Laravel API 发送 post 请求。
{
"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
}
正文字段是一个 JSON 数据字段 - JSON.stringify 编辑器 js 的输出。
我的 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
中使用jsonmysql
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/
我正在使用 postman 向我的 Laravel API 发送 post 请求。
{
"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
}
正文字段是一个 JSON 数据字段 - JSON.stringify 编辑器 js 的输出。
我的 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
中使用jsonmysqlNOTE : 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/