验证中的自定义多重属性

时间:2019-02-17 08:01:26

标签: laravel validation request attributes

我正在Laravel请求中使用验证。我想根据另一个属性的划分来处理一个属性。它如何控制?

    public function rules()
    {
       return [
               'number' => 'required|numeric',
               'threshold' =>['numeric',
                  function ($attribute, $value, $fail) {
                   if ($attribute > 'number/2') { 
                      $fail(('threshold must be smaller than division of number'));
                        } 
                    }, ]
                ];
    }

2 个答案:

答案 0 :(得分:1)

您可以在整个应用程序中全局使用request()功能, 因此,在这种情况下,您可以使用

来访问特定属性
$attribute_value = request()->YOUR_ATTRIBUTE;

答案 1 :(得分:1)

只需使用Laravel现在提供的prepareForValidation方法添加另一种方法即可:

在您的Request班上:

<?php
/**
 * Modify the input values
 *
 * @return void
 */
protected function prepareForValidation(){

    $this->merge[
        'number_division_by_2' => $this->input('number') / 2
    ];
}

然后在同一Request类的规则中,可以添加:

<?php 

public function rules()
{
   return [
           'number' => 'required|numeric',
           'threshold' =>'numeric',
           'number_division_by_2' => 'lt:threshold'
}