88 * "decimal" cast uses `number_format`, but we can utilize the `toFixed` method
99 * provided by Decimal\Decimal to prepare the value.
1010 *
11- * This trait does not provide a cast from string to Decimal; this should be
12- * done manually using an accessor like `getPriceAttribute`, which should return
13- * a new Decimal\Decimal using the precision of the column in the database.
11+ * This trait extends the default behavior by allowing the precision and scale
12+ * of the decimal value to be specified via the attribute's casting definition.
13+ * For example, `decimal:2:8` would cast the attribute to a Decimal with 2 digits
14+ * of scale and 8 digits of precision.
1415 */
1516trait DecimalObjectCast
1617{
@@ -27,7 +28,31 @@ trait DecimalObjectCast
2728 protected function asDecimal ($ value , $ decimals )
2829 {
2930 assert ($ value instanceof Decimal);
30-
31- return $ value ->toFixed ($ decimals , $ commas = false , PHP_ROUND_HALF_UP );
31+ $ decimals = explode (': ' , $ decimals )[0 ];
32+
33+ return $ value ->toFixed ($ decimals , false , PHP_ROUND_HALF_UP );
34+ }
35+
36+ /**
37+ * Set a given attribute on the model.
38+ *
39+ * @param string $key
40+ * @param mixed $value
41+ *
42+ * @return mixed
43+ */
44+ public function setAttribute ($ key , $ value )
45+ {
46+ if (null !== $ value ) {
47+ $ casts = $ this ->getCasts ();
48+ if (array_key_exists ($ key , $ casts ) && $ this ->isDecimalCast ($ casts [$ key ])) {
49+ $ precision = explode (': ' , $ this ->casts [$ key ])[2 ] ?? Decimal::DEFAULT_PRECISION ;
50+ $ this ->attributes [$ key ] = new Decimal ($ value , $ precision );
51+
52+ return $ this ;
53+ }
54+ }
55+
56+ return parent ::setAttribute ($ key , $ value );
3257 }
3358}
0 commit comments