I have a decimal field to represent money in my Eloquent Model and I'm noticing erroneous results when trying to add some number to this field.
Upon further inspection, I found that the decimal field is being cast as a string, like "1245114.00"
in the tinker console.
I checked the table structure and I can verify that the field is indeed decimal(11,3)
.
This question was asked before but has no answers.
Why is this happening?
You need to define in your model which fields need to be cast to a primitive attribute.
protected $casts = [ 'my_decimal' => 'float', ];
The
$casts
property on your model provides a convenient method of converting attributes to common data types. The$casts
property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are:integer
,real
,float
,double
,string
,boolean
,object
,array
,collection
,date
,datetime
, andtimestamp
There is a really good explanation here:
https://mattstauffer.com/blog/laravel-5.0-eloquent-attribute-casting/
Also there is an explanation in the docs:
https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With