在Laravel 5请求类中使用有时()函数 [英] Use sometimes() function in Laravel 5 request class

查看:66
本文介绍了在Laravel 5请求类中使用有时()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在laravel 4中,我使用了sometimes()方法,如下所示:

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

仅在显示recurrence时,通知integer|min:1才应用于recurring.

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

在laravel 5中,我尝试将验证实现为请求类:

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

就像从请求类中一样,我无法调用sometimes()方法.这样做的目的是避免在控制器上使用验证代码.

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

推荐答案

好吧,我已经模拟了使用自定义条件所期望的行为,而没有100%确定天气是最佳做法:

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;

这篇关于在Laravel 5请求类中使用有时()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆