Check Empty Fields - Laravel 5.3

2

I have an integer field and a date field that are not required and are programmed to accept NULL, but when I send the form data without filling in, my controller receives the empty value instead of ignoring the field, which generates the error:

  

Incorrect integer value: '' for column vendor_id

How can I resolve this?

Migration:

 $table->integer('vendedor_id')->unsigned()->nullable();
 $table->date('data_venda')->nullable();

Controller:

$new = $this->repository->create($request->all());

View:

<div id="vendedor_id" class="form-group col-sm-4 opt">
    <label for="vendedor_id">Vendedor:</label>
    <select name="vendedor_id" class="form-control select2">
        <option value=""></option>
        <option value="1">User 1</option>
        <option value="2">User 2</option>
    </select>
</div>
<div id="data_venda" class="form-group col-sm-4">
    <label for="data_venda">Data:</label>
    <input type="date" name="data_venda" class="form-control">
</div>

In my request I have some validations for the required fields, but it does not include anything about these 2 fields. Ex.:

public function rules()
{
    return [
        'cnpj' => 'numeric|required|cnpj|unique:empresas',
        'razao_social' => 'required',
    ];
}
    
asked by anonymous 02.12.2016 / 13:51

2 answers

5

I'll pass some solutions below that the framework itself offers:

Model Mutators

You can define a behavior for defining a particular attribute of a Model in Laravel.

For example, if you do not have to set any field checking conditions in your controller at all times, you can create a specific setter for these fields in your Model.

See:

  public function setVendedorIdAttribute($valor) {
      $this->attributes['vendedor_id'] = ctype_digit($valor) ? $valor : NULL;
  }

So, every time an empty value was passed, it would be inserted as NULL into the bank.

Validation

According to the documentation of Laravel 5.3 , it is possible, from this version, to define a validation nullable for a given field.

Array_Filter

Another solution would be to use array_filter which removes empty values from a array .

$data = array_filter($request->all());
$new = $this->repository->create($data);

Array_Map

If you just want to convert the empty values to NULL , you can also use array_map as a solution:

$data = array_map($request->all(), function ($value) {
  return $value ?: NULL;
});
    
02.12.2016 / 14:10
5

If no value is chosen at that select it is sending "" ai the problem lives, needs to be checked before sending to this layer repository :

$data = $request->except('vendedor_id');
$data['vendedor_id'] = $request->input('vendedor_id', "") == "" 
                      ? null
                      : (int)$request->input('vendedor_id')
$new = $this->repository->create($data);
    
02.12.2016 / 14:01