首页 > 解决方案 > 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."
        ]
    }
}

标签: phpjsonlaraveleditorjs

解决方案


尝试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/

https://laracasts.com/discuss/channels/laravel/saving-an-array-into-a-json-column-in-a-mysql-database


推荐阅读