Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent casts decimal as string

Tags:

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?

like image 209
Sapnesh Naik Avatar asked Jan 16 '18 19:01

Sapnesh Naik


1 Answers

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, and timestamp

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

like image 117
Luis felipe De jesus Munoz Avatar answered Oct 01 '22 05:10

Luis felipe De jesus Munoz