我正在使用自定义验证规则来验证从文件中读取的一些数据。规则如下:
$this->rules = [
'file_data' => 'required|array',
'file_data.*.id' => 'required',
'file_data.*.name' => 'required',
'file_data.*.code' => 'required|code_exists'
];
并应用这些规则,例如
$validationResult = validator($data, $this->rules, $customMessageArray);
在 code_exists
中,我需要 id
的值来运行验证。我试图通过 $parameters
传递值,例如 code_exists:id
,但它在参数数组中为我提供了字符串 id
。我怎样才能传递实际值?
最佳答案
您应该获取数组的键,然后获取 id。像这样:
'file_data.*.code' => [
'required',
function($attribute, $value, $fail) use ($data) {
$index = explode('.', $attribute)[1];
$id = data_get($data, "file_data.$index.id");
$isExists = DB::table('table_name')->whereId($id)->whereCode($value)->exists();
if (!$isExists) {
return $fail(__('validation.exists', ['attribute' => $attribute]));
}
}
],
关于php - 如何在 Laravel 自定义验证中获取其他字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57674238/