Is it possible to validate with the operator Or a FormRequest in laravel?

1

I have a form in which I show fines and consumptions, and a button that sends the selected elements. The question is whether you can make the 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 to choose both, so can it be with formRequest? or you should 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>';
}
    
asked by jeancarlos733 29.08.2017 в 07:36
source

1 answer

1

Perhaps the best solution to read and understand the driver code is split the validation in two and fail if that one of the two is not fulfilled:

<?php
/* Necesario para validar con Validator::make */
use Validator;
/* Normalmente usado para recibir los parámetros en el controlador */
use Illuminate\Http\Request;
/* Usado para crear una clase que actúa de controlador */
use App\Http\Controllers\Controller;

class TuControlador extends Controller
{
  public function tu_accion(Request $peticion)
  {
    $prueba1 = Validator::make($peticion->all(), [
      'consumos' => 'required',
    ]);
    $prueba2 = Validator::make($peticion->all(), [
      'multas' => 'required',
    ]);
    if ($prueba1->fails() || $prueba2->fails()) {
      /* Hacer lo que quieras cuando falle la comprobación */
    }
    /* Hacer lo que quieras si el formulario cumple las condiciones */
  }
}

Another solution (which I have not tried) would be a cyclical dependence, it can be complicated when there are many dependencies and it is probably more difficult to maintain:

return [
  'consumos' => 'required_without:multas',
  'multas' => 'required_without:consumos',
];
    
answered by 29.08.2017 / 08:59
source