【问题标题】:Laravel(5.3.24+) Validation: Validate 2 columnsLaravel(5.3.24+) 验证:验证 2 列
【发布时间】:2017-03-13 16:01:35
【问题描述】:

使用这里看到的新风格的 laravel 验证:https://laravel-news.com/unique-and-exists-validation

我希望 name 列是必需的,并且仅在比赛中是唯一的。

使用下面的示例表, id 3:验证应该阻止这种情况发生,因为“该比赛的名称已经存在”。

【问题讨论】:

    标签: validation laravel-5.3


    【解决方案1】:

    自定义规则

    最好的解决方案是为此创建一个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 是否已经存在类似的名称。

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 2020-06-10
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 2015-06-06
      相关资源
      最近更新 更多