Laravel验证:存在其他列条件-自定义验证规则 [英] Laravel validation: exists with additional column condition - custom validation rule
问题描述
在Laravel中指定存在的验证规则时,是否可以引用另一个字段?我想说的是,输入a必须存在于表a中,输入b必须存在于表b中,并且表b中x列的值必须等于输入a.
Is there is a way of referencing another field when specifying the exists validation rule in Laravel? I want to be able to say that input a must exist in table a, input b must exist in table b AND the value for column x in table b must equal input a.
最佳示例解释:
public $rules = array(
'game_id' => 'required|exists:games,id',
'team1_id' => 'required|exists:teams,id,game_id,<game_id input value here>',
'team2_id' => 'required|exists:teams,id,game_id,<game_id input value here>'
);
因此,根据我的验证规则,我希望能够确保:
So with my validation rules I want to be able to make sure that:
-
game_id
存在于games
表(id
字段)中 -
team1_id
存在于teams
表(id
字段)中,并且game_id
列(在teams
表中)必须等于game_id
输入的值. - 与上述
team2_id
相同
game_id
exists within thegames
table (id
field)team1_id
exists within theteams
table (id
field) and thegame_id
column (in theteams
table) must equal the value of thegame_id
input.- As above for
team2_id
因此,如果在我的表单中,我为game_id
输入1
,则我希望能够确保team1_id
和team2_id
的teams表中的记录的值都为1
game_id
.
So, if in my form, I entered 1
for game_id
, I want to be able to ensure that the record within the teams table for both team1_id
and team2_id
have the value 1
for game_id
.
我希望这是有道理的.
谢谢
推荐答案
您需要自定义验证规则,为此我将创建一个单独的类.但是为了简洁起见,使用内联闭包几乎是相同的:
You want a custom validation rule, and I would create a separate class for this. But for brevity here's pretty much the same using inline closure:
// give it meaningful name, I'll go with game_fixture as an example
Validator::extend('game_fixture', function ($attribute, $value, $parameters, $validator)
{
if (count($parameters) < 4)
{
throw new \InvalidArgumentException("Validation rule game_fixture requires 4 parameters.");
}
$input = $validator->getData();
$verifier = $validator->getPresenceVerifier();
$collection = $parameters[0];
$column = $parameters[1];
$extra = [$parameters[2] => array_get($input, $parameters[3])];
$count = $verifier->getMultiCount($collection, $column, (array) $value, $extra);
return $count >= 1;
});
然后简单地使用:
$rules = array(
'game_id' => 'required|exists:games,id',
// last parameter here refers to the 'game_id' value passed to the validator
'team1_id' => 'required|game_fixture:teams,id,game_id,game_id',
'team2_id' => 'required|game_fixture:teams,id,game_id,game_id'
);
这篇关于Laravel验证:存在其他列条件-自定义验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!