laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

if a column is not null, and it has default value empty string. `Model::create()` deson't work very well. #1214

Open allowing opened 6 years ago

allowing commented 6 years ago
  1. there is a column, it is not null, but it has empty string default value.
  2. laravel's middleware ConvertEmptyStringsToNull

$data = $request->validate([
    'name' => 'required|string|max:255',
    'gender' => 'integer',
    'age' => 'integer',
]);

// if `$data['gender']` is null, (by ConvertEmptyStringsToNull)

// deson't work very well sometimes
$p = new Person($data);
$p->save();

// deson't work very well sometimes, too
Person::create($data);
michaeldyrynda commented 6 years ago

You can just disable the ConvertEmptyStringsToNull middleware in your App\Http\Kernel if this is causing you trouble.

allowing commented 6 years ago

@michaeldyrynda Yes, I can. but the reason for this problem is not ConvertEmptyStringsToNull.

michaeldyrynda commented 6 years ago

In that case, can you clarify what you meant when you said that it doesn't work very well sometimes? Are you getting errors, or some other measure of "not working"?

If you have a default of empty string and haven't marked the column as nullable, you won't be able to insert a null value into it. Laravel doesn't know your database schema in code, so you won't get an error like that until you try and insert invalid data to the database.

sisve commented 6 years ago

This sounds like an attempt to chat with support, not an idea for Laravel. Have you considered using the forums at Laracasts or perhaps the Slack to have a real chat instead?

allowing commented 6 years ago

I mean, can have some validators like this: if_null_set:'', if_null_remove_the_item, if_empty_string_set:null

I am getting errors: _20180611135023

sisve commented 6 years ago

Database default values are only used if none is provided by the application. You provide a value, null, which is invalid. Use a mutator to store empty strings in case of nulls.

michaeldyrynda commented 6 years ago

You could also use TrimStrings instead of ConvertEmptyStringsToNull. Validation shouldn’t manipulate the request data as you suggested.

allowing commented 6 years ago

I'm now using this way:


public function setNoteAttribute($value)
{
    if (is_null($value)) {
        $this->attributes['note'] = '';
    }
}
AhmedHelalAhmed commented 4 years ago

You can filter the array of data like that

$p = new Person(array_filter($data));