laravel - Laravel:为 json 字段/列定义规则或模式
问题描述
我的数据库中有一个列,它是 json 类型:values
.
但我需要强制执行模式。
- 它必须是一个数组
- 每个对象必须有 2 个且只有 2 个属性(必需)。
code_name
, 和description
code_name
在该 JSON 数组中必须是唯一的
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
解决方案
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,
];
推荐阅读
- multithreading - S3Client 与 S3AsyncClient
- angular - 错误:无效响应内容类型:文本/html
- c++ - 我无法理解静态指针的用途
- java - BigDecimal 格式
- javascript - 为某些分辨率添加元素
- sql - 查找子表包含给定参数中所有 Id 的所有行
- angular - Angular:有没有办法在不排序的情况下迭代 Map<,>?
- python-3.x - 如何在 Python 多处理中通信两个并行进程(不终止)?
- javascript - 如何用方法替换 JavaScript 替换三重反斜杠
- javascript - Wrapper 不会占用全部空间