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

查看:42
本文介绍了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>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_id 的团队表中的记录team2_idgame_id 的值为 1.

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天全站免登陆