Shokouh Dareshiri
Shokouh Dareshiri

Reputation: 946

Custom multi attributes in validation

I am using validation in Request of Laravel. I would like handle a attribute base on division of another attribute. How could it control?

    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'));
                        } 
                    }, ]
                ];
    }

Upvotes: 0

Views: 96

Answers (2)

Mihir Bhende
Mihir Bhende

Reputation: 9045

Just adding another way of doing this using prepareForValidation method now available in Laravel :

In your Request class :

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

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

Then in your rules of the same Request class, you can add :

<?php 

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

Upvotes: 1

Soheil Rahmat
Soheil Rahmat

Reputation: 521

You can use request() function globally all over your app, So, in this case for accessing specific attribute you can use

$attribute_value = request()->YOUR_ATTRIBUTE;

Upvotes: 1

Related Questions