Fields in a form that are not completed are saved as NULL in the database or ignored in the query

1

I have a form with different inputs, of which the vast majority are not necessary to fill (and some of these are inputs that are related to other tables), my question is, when these inputs are empty, how do I do that are not added in the insert to the database or to be inserted but with a null value?

The inputs of type "text" that are in the insert / update and that in the table are of type varchar do not throw error because they are stored as NULL type, however all others (checkbox, select or inputs that have to send numbers) no, they throw error at the time of executing the query, try leaving them the value="" but the same does not work.

Would I have to do a previous check in the controller or is it something that has to be configured in the same database?

I hope I have been specific enough, thank you!

    
asked by Liski 21.02.2017 в 15:01
source

2 answers

1

If I understand the problem well, what you want to do is store some values in null when they are empty in the form or when they have a certain value.

Laravel 5.4 includes a middleware that is responsible for converting the empty strings of the request to null .

<?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;
    }
}

On the other hand, you do not need to write the value null in the database, you simply add the modifier nullable to the fields that need it, so you can define it in the migration, and its default value will be null .

An example taken from the documentation:

Schema::table('users', function (Blueprint $table) {
    $table->string('email')->nullable();
});

More information: link

    
answered by 21.02.2017 в 17:43
0

You could set a value that you will never use, for example value="-1"

and in your php post code put something like

if($_POST['nameDeTuInput'] == '-1') {
  $valor = NULL;
}

and then you store value in the insert query, or another option if you are not going to use it as disabled in the html using a checkbox, then it will not be sent by the POST method and and you can use

if(isset($_POST['nameDeTuInput'])) {
  $valor = NULL;
}
    
answered by 21.02.2017 в 15:29