How can I modify a field to integrate and return it null or empty? from laravel in DB postgresql

0

The table is as follows:

CREATE TABLE public.productos_procesos
(
  id integer NOT NULL DEFAULT nextval('productos_procesos_id_seq'::regclass),
  id_productos integer NOT NULL,
  id_procesos integer NOT NULL,
  unidad_teorica integer,
  id_unidades_de_medicion integer,
  velocidad integer,
  created_at timestamp(0) without time zone,
  updated_at timestamp(0) without time zone,
  tiempo_teorico character varying(255) DEFAULT '0:0:0'::character varying,
  valid boolean DEFAULT true,
}

And when I try to modify a field of integer type and return it null it throws me the following error:

SQLSTATE [22P02]: Invalid text representation: 7 ERROR: the input syntax is not valid for integer: «» (SQL: update "products_processes" set "theoretical_id" =, "media_id_id" =, "speed" =, "updated_at" = 2017-03-15 17:52:13, "valid" = false where "id" = 121)

Controller:

$result = Productos_Procesos::findOrFail($req->productos[$i]);
$valores = array(
    'valid' => $req->valid[$i],
    'unidad_teorica' => $req->unidad_teorica[$i],
    'id_unidades_de_medicion' => $req->unidad_de_medicion[$i],
    'velocidad' => $req->velocidad[$i],
    'tiempo_teorico' => $req->tiempo_teorico[$i],
);
$result->update($valores);

The array that I create is the following:

array:5 [
  "valid" => "false"
  "unidad_teorica" => ""
  "id_unidades_de_medicion" => ""
  "velocidad" => ""
  "tiempo_teorico" => ""
]
    
asked by Pablo Contreras 15.03.2017 в 18:56
source

2 answers

1

Your array should be null instead of empty ""

array:5 [
  "valid" => "false"
  "unidad_teorica" => null //envias la variable como null y no como vacío
  "id_unidades_de_medicion" => ""
  "velocidad" => ""
 "tiempo_teorico" => ""

]

    
answered by 15.03.2017 / 19:01
source
1

As a reference for other future visitors, from Laravel 5.4 there is a middleware that is responsible for converting the empty strings of a request into null, and thus avoid this type of inconvenience.

Although the answer chosen is correct, in the future the best practice (at least until now) is to use the middleware.

This middleware is called ConvertEmptyStringsToNull and is included by default in the stack located in App\Http\Kernel .

The code of said middleware is the following:

<?php

namespace Illuminate\Foundation\Http\Middleware;

class ConvertEmptyStringsToNull extends TransformsRequest
{
    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        return is_string($value) && $value === '' ? null : $value;
    }
}
    
answered by 15.03.2017 в 20:15