Use sometimes() function in Laravel 5 request clas

2019-07-23 22:03发布

问题:

In laravel 4, I used the sometimes() method as below:

$validator = \Validator::make(
        \Input::all(),
        array(
            'name' => array('required'),
            'recurrence' => array('required_if:recurring,on'),
        )
    );

$validator->sometimes('recurrence', 'integer|min:1', function($input) {
    return $input->recurring == 'on';
});

Notice integer|min:1 are applied to recurring only if recurrence is presented.

In laravel 5, I tried to implement the validation as a request class:

class CreateProductRequest extends Request {

    public function authorize(){
        return true;
    }

    public function rules(){
        return [
            'name' => array('required'),
            'recurrence' => array('required_if:recurring,on'),
        ];
    }
}

Looks like from a request class I am unable to call sometimes() method. The idea is to avoid validation code at controller.

回答1:

Ok, I have emulated the behaviour expected using a custom condition without be 100% sure weather is the best practice:

$rules = [
    'name' => array('required'),
    'recurrence' => array('required_if:recurring,on'),
];

if ($this->has('recurring')){
    $rules['recurrence'] = $rules['recurrence'] + ['integer', 'min:1'];
}

return $rules;