Laravel(5.3.24+)验证:验证2列
Laravel(5.3.24+) Validation: Validate 2 columns
使用此处看到的 laravel 验证的新样式:https://laravel-news.com/unique-and-exists-validation
我希望名称列是必填项,并且仅在比赛中是唯一的。
使用下面的示例 table,
id 3:验证应该阻止这种情况发生,因为 "a name already exist for that competition".
自定义规则
最好的解决方案是为此创建一个 custom rule,它接受具有相应 competition_id 的字段作为参数。
类似
//Calling the custom rule like this
['name' => 'required|validateName:yourCompetitionIdFormFieldHere'];
像这样在您的服务提供商中声明自定义验证函数
Validator::extend('validateName', function ($attribute, $value, $parameters, $validator) {
$competitionId = ($validator->data, $parameters[0]);
//Now check if the $value is already set for the specific competition_id by using normal database queries and comparison
return count(Team::where("comeptition_id", "=", $competitionId)->whereName($value)->get()) == 0
});
它是做什么的
自定义验证规则接收您用函数提供的字段数据(在上面的代码中是yourCompetitionIdFormFieldHere
),因此它知道用户选择了哪个league/competition_id。有了这些信息,您现在可以检查输入的 ID 是否已经有相似的名称。
使用此处看到的 laravel 验证的新样式:https://laravel-news.com/unique-and-exists-validation
我希望名称列是必填项,并且仅在比赛中是唯一的。
使用下面的示例 table, id 3:验证应该阻止这种情况发生,因为 "a name already exist for that competition".
自定义规则
最好的解决方案是为此创建一个 custom rule,它接受具有相应 competition_id 的字段作为参数。
类似
//Calling the custom rule like this
['name' => 'required|validateName:yourCompetitionIdFormFieldHere'];
像这样在您的服务提供商中声明自定义验证函数
Validator::extend('validateName', function ($attribute, $value, $parameters, $validator) {
$competitionId = ($validator->data, $parameters[0]);
//Now check if the $value is already set for the specific competition_id by using normal database queries and comparison
return count(Team::where("comeptition_id", "=", $competitionId)->whereName($value)->get()) == 0
});
它是做什么的
自定义验证规则接收您用函数提供的字段数据(在上面的代码中是yourCompetitionIdFormFieldHere
),因此它知道用户选择了哪个league/competition_id。有了这些信息,您现在可以检查输入的 ID 是否已经有相似的名称。