Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate only if the field is entered in Laravel 5.2

public function rules() {
        return [
            'num_of_devices' => 'integer'
        ];
}

I want to validate an integer field if and only if the field is entered. But above rule validates it for integer even if the field is empty. I used somtimes, but no result. But when I var_dump($num_of_devices) it is string.I am using Laravel 5.2. I think It was working fine in 5.1.

like image 533
Kiren S Avatar asked Nov 28 '22 20:11

Kiren S


2 Answers

From version 5.3 you can use nullable

public function rules() {
        return [
            'num_of_devices' => 'nullable | integer'
        ];
}
like image 149
nasor Avatar answered Dec 04 '22 03:12

nasor


Add a rule to array, if input is not empty. You could collect all your validation rules to $rules array and then return the array.

if( !empty(Input::get('num_of_devices')) ){
  $rules['num_of_devices'] = 'integer';
}
like image 42
Timo Avatar answered Dec 04 '22 04:12

Timo