Condition in request laravel

2

I have a request class called PessoaRequest . In this class, I validate my registration form for people.

But now, some information to be inserted appears that is not mandatory: the name of the father and the mother. When I have this information, I set a checkbox that creates the html fields to enter this data.

In class PessoaRequest , I have the following rules:

return [
      'name'       => 'required|min:3|alpha', //obrigatório com pelo menos 3 caracteres alfabéticos
      'telefone_1' => 'required',//obrigatório e deve ser um email
      'email'      => 'required'
      [....]
    ];

In it, I can not place a rule for the fields that ask for the name of the father and the mother, since they are not mandatory.

I would like to know if you can put conditional rule inside Request , type:

// Se o checkbox for marcado
if($chkPais == 1 ) {
      'nome_pai' => 'required',
      'nome_mae' => 'required'
}

If not, how could you do this validation?

Thank you in advance.

    
asked by anonymous 18.04.2016 / 20:43

1 answer

4

Yes, I usually do this a lot in Laravel 5 .

public function rules() 
{
    $rules = ['nome' => 'required', 'email' => 'required|email'];

    // Se o valor da checkbox for marcado

    if ($this->has('check_box'))
    {
         $rules['pai'] = 'required';
         $rules['mae'] = 'required';
    }


    return $rules;
}

You only add the validations of pai and mae if the value of your checkbox is checked.

Just remembering that when we create a Request , we are extending the Request default used in Laravel . Then, through the pseudo variable $this , we can access methods like get , has and only .

The has method in this case is to check if any check_box field was sent by a form. If empty, has will return false . However, if you return something, it will drop to if , which will add% to $rules to% valid% and pai to validation.     

18.04.2016 / 20:47