Reputation: 6435
I have a field in my database table called service_3_total
which is of type decimal(10,2)
. I have set this to be a nullable()
field in my migrations so in my database Null = Yes and Default = NULL.
If I leave this field blank when submitting my form I get the following error:
General error: 1366 Incorrect decimal value: '' for column 'service_3_total'
I have no idea why I'm getting this as I have allowed this field to be null in the database. I think it has something to do with the fact that it is a decimal data type.
Any Ideas?
Upvotes: 1
Views: 5390
Reputation: 1413
class YourModel extends Model
{
protected static function boot()
{
static::creating(function ($model) {
$model->service_3_total = empty($model->service_3_total) ? null : $model->service_3_total ;
});
static::updating(function ($model) {
$model->service_3_total = empty($model->service_3_total) ? null : $model->service_3_total ;
});
}
}
You can use function before create/update to convert blank
value to null
inside your model to prevent messing around controller, let's model
manage data
Upvotes: 1
Reputation: 1314
"service_3_total" => "". If you are setting the column value to an empty string and passing the entire array to be executed, you will get an error because empty string is a string type and is not Equivalent to NULL. You should unset this key in the array for SQL to execute the default.
Upvotes: -1
Reputation: 3890
In your comment you state that the value for variable to insert is:
"service_3_total" => ""
Empty string !== null
You are passing a blank string instead of null, so MySQL is erroring out trying to parse that "" into a number.
Something like this could work in your code. Just add this before the insert. (make it more elegant depending on your usecase, this is just to make it work without error)
if (!$data['service_3_total']) {
$data['service_3_total'] = null;
}
When you try this now, MySQL will correctly identify the value as null and enter it as such in the DB, blank string won't work.
Upvotes: 8