Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multi required_if in laravel?

1) I am new to laravel and want to integrate validation rules. My requirement is to make third field mandatory on basis of two other fields. Field C is required if both a and b are true. I have used required_if to put validation on basis of other single field but how can i use required_if to check two fields?

2) To achieve above functionality i tried custom validation rule as well. But it's working only if i will pull required rule alongwith.

For example:

'number_users' => 'required|custom_rule'   //working 
'number_users' => 'custom_rule'   //Not working
like image 745
dirtyhandsphp Avatar asked Apr 13 '15 15:04

dirtyhandsphp


1 Answers

You can use conditional rules for that.

Here's a simple example:

$input = [
    'a' => true,
    'b' => true,
    'c' => ''
];

$rules = [
    'a' => 'required',
    'b' => 'required'
    // specify no rules for c, we'll do that below
];

$validator = Validator::make($input, $rules);

// now here's where the magic happens
$validator->sometimes('c', 'required', function($input){
    return ($input->a == true && $input->b == true);
});

dd($validator->passes()); // false in this case
like image 118
lukasgeiter Avatar answered Oct 27 '22 03:10

lukasgeiter