我的数据库中有一列,其列为json类型:values
。
但是我需要执行一个模式。
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)
];
但这还不够。
的重复问题答案 0 :(得分:3)
Laravel支持添加您自己的自定义验证规则。
要创建验证规则,您应该创建一个新类来实现Illuminate\Contracts\Validation\Rule
接口。
工匠命令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,
];