When trying to convert a VARCHAR column value from the database that has NULL as default value, the cast property on my Eloquent model is ignored and my attribute does not get converted due to this logic:
https://github.com/illuminate/database/blob/607d5e1c8e2ecc61d312a455a5e93d6793f694df/Eloquent/Concerns/HasAttributes.php#L458-L460
Add this to a Eloquent model and get a VARCHAR column that has NULL as default value.
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'products_stock_attributes' => 'string'
];
Surely this is the desired behaviour?
I don't understand the issue, If you trying to set default value for null like
string => '',
you need to define it in the attributes property
protected $attributes= [
'products_stock_attributes' => ''
];
I have a VARCHAR column in my database that is NULLABLE, so it can return from the database as null and as an empty string if it is set but as an empty value, I would prefer to do a string conversion so I only have to check against empty string and forget about NULL values.
// this is what I have to do without a null -> string conversion
if ($value !== null && $value !== '') {}
// this is what I would like to do
if ($value !== '') {}
How about if (empty($value)) { or if (!$value) {?
well sure there are walkarounds for this issue, but is there any reason for why you cannot cast null values? I use strict comparison throughout my repository.
In my apps, if I have a nullable field I would want it to return null. If you want an empty field just put an empty string in the DB.
I think it's the desired behaviour, null is not an empty string and not a zero. Casting null to zero for integers or empty string for strings is not always desired.
Alright, guess I have to create an accessor method that does the job then if I cannot use $casts, thanks guys.
I was just running into this because I have legacy tables in which there is a nullable boolean column. I wanted laravel to always cast null to false. The casts property alone does not solve for this. Instead, you can rely on setting the default attributes property to set the default to false when the value is null.
EDIT: This solution unfortunately doesn't work for existing database values. I've created a package to solve for this: https://github.com/mr-feek/eloquent-null-casts
Most helpful comment
I think it's the desired behaviour,
nullis not an empty string and not a zero. Castingnullto zero for integers or empty string for strings is not always desired.