【发布时间】:2017-03-13 16:01:35
【问题描述】:
使用这里看到的新风格的 laravel 验证:https://laravel-news.com/unique-and-exists-validation
我希望 name 列是必需的,并且仅在比赛中是唯一的。
使用下面的示例表, id 3:验证应该阻止这种情况发生,因为“该比赛的名称已经存在”。
【问题讨论】:
使用这里看到的新风格的 laravel 验证:https://laravel-news.com/unique-and-exists-validation
我希望 name 列是必需的,并且仅在比赛中是唯一的。
使用下面的示例表, id 3:验证应该阻止这种情况发生,因为“该比赛的名称已经存在”。
【问题讨论】:
最好的解决方案是为此创建一个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),因此它知道用户选择了哪个联赛/比赛ID。有了这些信息,您现在可以检查输入的 id 是否已经存在类似的名称。
【讨论】: