首页 > 解决方案 > Laravel:为 json 字段/列定义规则或模式

问题描述

我的数据库中有一个列,它是 json 类型:values.
但我需要强制执行模式。

Laravel 是否为此提供了一些开箱即用的功能?还是我需要在创建和更新时手动解码 json 以验证该规则?

直到现在。我的模型中只有这个验证规则:

/**
 * The model validation rules.
 *
 * @var array
 */
public static $rules = [
    'values' => 'required|json', // TO BE CHECKED (values validation (json schema) and setter)
];

但这还不够。

重要:这不是重复的问题:Laravel: validate json object

标签: laravelvalidationlaravel-5

解决方案


Laravel 支持添加您自己的自定义验证规则。

要创建验证规则,您应该创建一个实现接口的新类Illuminate\Contracts\Validation\Rule

artisan 命令php artisan make:rule {NAME}会在命名空间中自动为您生成规则模板App\Rules

简而言之,您编写了一个passes($attribute, $value)函数,该函数返回一个布尔值,用于确定验证是失败还是成功。

我在下面根据您的要求编写了一个示例。

例子

<?php
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ValuesSchemaRule implements Rule
{
    private $validProperties = ['code_name', 'description'];

    public function __construct()
    {
    }

    public function passes($attribute, $value)
    {
        $array = json_decode($value);

        if (is_array($array) === false) {
            return false;
        }

        $codeNames = [];

        foreach ($array as $object) {
            $properties = get_object_vars($object);

            if (count($properties) !== 2) {
                return false;
            }

            $propertyNames = array_keys($properties);

            if (in_array($this->validProperties, $propertyNames) === false) {
                return false;
            }

            array_push($codeNames, $object->code_name);
        }

        if (count($codeNames) !== count(array_unique($codeNames))) {
            return false;
        }

        return true;
    }

    public function message()
    {
        return 'The values does not comply to the JSON schema';
    }
}

要将其添加到模型验证中,您只需将该'values'属性分配给 Rule 类的新实例:

/**
 * The model validation rules.
 *
 * @var array
 */
public static $rules = [
    'values' => new ValuesSchemaRule,
];

推荐阅读