Home > Enterprise >  Eloquent can't store decimal values
Eloquent can't store decimal values

Time:05-18

I've been trying to save the product weight in a database field table with the type of decimal.

My code:

$p = Product::find($id)->update([
    'weight' => $product['weight'] ? floatval($product['weight']) : null,
]);

It always rounds up the number for some reason, even though dd(floatval($product['weight'])) outputs the correct value, when i try to save it it doesn't save the correct value, only changing the field to the type of float works, but i read that it is not a correct approach.

I'm using MySQL and the Laravel 8.75.

CodePudding user response:

Decimal type in MySQL has two tuning knobs: precision and scale. You omitted the scale, so it defaults to 0.

Documentation (link)

The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.1 are as follows:

M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions of MySQL permitted a range of 1 to 254.)

D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.

Example

mysql> create table test01 (field01 decimal(9));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into test01 (field01) values (123.456);
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from test01;
 --------- 
| field01 |
 --------- 
|     123 |
 --------- 
1 row in set (0.00 sec)

mysql> create table test02 (field01 decimal(9, 4));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into test02 (field01) values (123.456);
Query OK, 1 row affected (0.01 sec)

mysql> select * from test02;
 ---------- 
| field01  |
 ---------- 
| 123.4560 |
 ---------- 
1 row in set (0.00 sec)

CodePudding user response:

Probably modifying the column with a migration

 Schema::table('products', function (Blueprint $table) {
        $table->decimal('weight', 9, 4)->change();
    });

Documentation

  • Related