I have a form in which I show fines and consumptions, and a button that sends the selected items. The question is whether it can be made to FormRequest
validate that one of the two is sent.
return [
'consumos'=>'required',
'multas'=>'required'
];
The previous code does not work for me because it forces me to choose both, so can it be done with formRequest? or should it validate with javascript
before submitting the form. Thanks.
Solution
public function generarPago(Request $peticion)
{
$num_medidor = $peticion->get('num_medidor');
$prueba1 = Validator::make($peticion->all(), [
'consumos' => 'required',
]);
$prueba2 = Validator::make($peticion->all(), [
'multas' => 'required',
]);
if ($prueba1->fails() && $prueba2->fails()) {
return redirect('http://localhost/getHistorial/'.$num_medidor)
->withErrors('Para generar el pago es necesario seleccionar una multa o un consumo.')
->withInput();
}else if(!$prueba1->fails()){
foreach ($peticion->get('consumos') as $m)
{
$this->pconsumo($num_medidor, $m);
}
}else{
foreach ($peticion->get('multas') as $m)
{
$this->pmulta($num_medidor, $m);
}
}
}
public function pmulta($num_medidor, $id)
{
echo 'Multa '.$id. ' Cancelada! <br>';
}
public function pconsumo($num_medidor, $id)
{
echo 'Consumo '.$id. ' Cancelado! <br>';
}
Perhaps the best solution to read and understand the controller code is to split the validation in two and make it fail in case one of the two is not met:
Another solution (which I haven't tried) would be a cyclic dependency, it can get tricky when there are many dependencies and probably more difficult to maintain: