在Laravel中指定存在的验证规则时,是否有一种引用另一个字段的方法?我希望能够说输入a必须存在于表a中,输入b必须存在于表b中,并且表b中列x的值必须等于输入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,<game_id input value here>' );
因此,根据我的验证规则,我希望能够确保:
> game_id存在于游戏表中(id字段)
> team1_id存在于teams表(id字段)中,game_id列(在teams表中)必须等于game_id输入的值.
>如上所述team2_id
因此,如果在我的表单中,我为game_id输入1,我希望能够确保team1_id和team2_id的teams表中的记录对于game_id具有值1.
我希望这是有道理的.
谢谢
你想要一个
custom validation rule,我会为此创建一个单独的类.但为简洁起见,使用内联闭包几乎相同:
原文链接:https://www.f2er.com/laravel/138930.html// 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,// last parameter here refers to the 'game_id' value passed to the validator 'team1_id' => 'required|game_fixture:teams,game_id','team2_id' => 'required|game_fixture:teams,game_id' );