{"id":"2b1c41e7d954acf6","repo":"laravel/framework","slug":"unable-to-cast-value-to-a-decimal","errorCode":null,"errorMessage":"Unable to cast value to a decimal.","messagePattern":"Unable to cast value to a decimal\\.","errorType":"exception","errorClass":"MathException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php","lineNumber":1541,"sourceCode":"            default => (float) $value,\n        };\n    }\n\n    /**\n     * Return a decimal as string.\n     *\n     * @param  float|string  $value\n     * @param  int  $decimals\n     * @return string\n     *\n     * @throws \\Illuminate\\Support\\Exceptions\\MathException\n     */\n    protected function asDecimal($value, $decimals)\n    {\n        try {\n            return (string) BigDecimal::of((string) $value)->toScale($decimals, RoundingMode::HalfUp);\n        } catch (BrickMathException $e) {\n            throw new MathException('Unable to cast value to a decimal.', previous: $e);\n        }\n    }\n\n    /**\n     * Return a timestamp as DateTime object with time set to 00:00:00.\n     *\n     * @param  mixed  $value\n     * @return \\Illuminate\\Support\\Carbon\n     */\n    protected function asDate($value)\n    {\n        return $this->asDateTime($value)->startOfDay();\n    }\n\n    /**\n     * Return a timestamp as DateTime object.\n     *\n     * @param  mixed  $value","sourceCodeStart":1523,"sourceCodeEnd":1559,"githubUrl":"https://github.com/laravel/framework/blob/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L1523-L1559","documentation":"The 'decimal:N' cast uses brick/math BigDecimal to scale the value. If the stored/assigned value cannot be parsed as a number, BigDecimal throws and Eloquent wraps it as MathException('Unable to cast value to a decimal.').","triggerScenarios":"Storing a non-numeric string in a decimal-cast column, e.g. $model->price = 'N/A' with 'price' => 'decimal:2'; importing a CSV where a decimal cell contains currency symbols or whitespace; null coerced to string under unusual drivers.","commonSituations":"Currency/price fields receiving formatted strings ('$1,234.50'); Excel/CSV import with locale-aware decimals; JSON API sending strings with units; mismatched cast precision vs. column type.","solutions":["Sanitize input to a plain numeric string before assignment: cast/strip symbols and thousands separators.","Use a normalizer: $value = filter_var($input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION).","If the column legitimately holds non-numeric data, change the cast to 'string' or 'json'."],"exampleFix":"// before\n$model->price = '$1,234.50'; // cast 'decimal:2' -> throws\n\n// after\n$model->price = filter_var('$1,234.50', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);","handlingStrategy":"validation","validationCode":"if (is_string($value) && ! is_numeric($cleaned = preg_replace(['/[^0-9.\\-]/'], '', $value))) {\n    throw new \\InvalidArgumentException('Cannot cast to decimal: ' . $value);\n}\n$model->price = $cleaned ?? $value;","typeGuard":"function isDecimalSafe(mixed $v): bool\n{\n    return is_numeric($v) || (is_string($v) && is_numeric(preg_replace('/[^0-9.\\-]/', '', $v)));\n}","tryCatchPattern":"try {\n    $model->price = $value;\n} catch (\\Illuminate\\Support\\Exceptions\\MathException $e) {\n    if (str_contains($e->getMessage(), 'cast value to a decimal')) {\n        $model->price = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);\n    } else {\n        throw $e;\n    }\n}","preventionTips":["Normalize currency/price inputs (strip symbols, thousands separators) before assigning.","Use a Form Request rule (numeric|decimal) on incoming decimal fields.","Validate CSV/Excel imports against is_numeric before persistence."],"tags":["eloquent","cast","decimal","math","data-import"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}