Laravel MySQL Check if there is a record

0

Could someone help me to correct my laravel code so that before inserting a new record, check if that record exists? (to avoid duplicates) that is, if there is a record equal to the one to be inserted, do not allow registration, otherwise allow it to be inserted.

It is worth mentioning that what I want to validate is a foreign column and it arrives as a value in a formula of formulurio. So far I have the following:

    $ciclo=$request->idCiclo; //Guardo el valor que recibo del formulario

    $existencia = DB::table('planespago')   //realizo la sentencia para saber si existe
    ->select('idCiclo')
    ->where('idCiclo', '=', $ciclo);

   if ($existencia = $ciclo) {   //aqui valido si son iguales en el campo de la db y 
                                  lo que llego del formulario
       return json_encode('no puedes registrar otro');

    }else{

      return  json_encode('creado');

    }

But the validation does not do me good and it passes directly that it is true even though I choose a value that does not exist

    
asked by Juan Antonio 12.06.2018 в 19:41
source

3 answers

1

Possibly due to typographical errors.

First in your query you need to use the get method to bring the data

$existencia = DB::table('planespago')
    ->select('idCiclo')
    ->where('idCiclo', '=', $ciclo)
    ->get();

And in your validation you are using only a = to make your condition, when you should use ==

if ($existencia == $ciclo)

If it is not due to that, it is possible that in your conditional you are comparing badly the variables and you should change to this:

if ($existencia->idCiclo == $ciclo)

The other way of solution is to change the condition to:

if(count($existencia) >= 1) 
    
answered by 12.06.2018 в 19:50
0

You save the value that $ request brings in the position "idCiclo", perfect keep in mind that this is an INT therefore you must compare it with a data that is of a similar type.

$ciclo=$request->idCiclo;

We summarize this line of code a little by making the query directly to the model (with the method find () it is not necessary to say get ()), keep in mind that here an OBJECT of the PlanesPago class is returned.

$existencia = PlanesPago::find($ciclo);

This is where you have the error, you are comparing a variable of type INT with a variable of type PlanesPago

if ($existencia = $ciclo)

The correct way would be

if($exitencia->idCiclo == $ciclo)

I would even say that you can implement the "===" operator since they are the same type.

I hope this is helpful.

    
answered by 13.06.2018 в 22:45
0

It's simpler than that, we have a helper that returns a Boolean

DB::table('planespago')->where('idCiclo', $idCiclo)->exists();
    
answered by 14.06.2018 в 17:06