Laravel验证:存在其他列条件-自定义验证规则 [英] Laravel validation: exists with additional column condition - custom validation rule

查看:425
本文介绍了Laravel验证:存在其他列条件-自定义验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 the games table (id field)
  • team1_id exists within the teams table (id field) and the game_id column (in the teams table) must equal the value of the game_id input.
  • As above for team2_id

因此,如果在我的表单中,我为game_id输入1,则我希望能够确保team1_idteam2_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆