Skip to content

Commit b76f575

Browse files
committed
Cast to native mongo Decimal128
1 parent 3d11dd2 commit b76f575

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

src/Eloquent/Model.php

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,16 @@ public function setAttribute($key, $value)
237237
{
238238
$key = (string) $key;
239239

240-
// Add casts
241-
if ($this->hasCast($key)) {
242-
$value = $this->castAttribute($key, $value);
240+
$casts = $this->getCasts();
241+
if (array_key_exists($key, $casts)) {
242+
$castType = $this->getCastType($key);
243+
$castOptions = Str::after($casts[$key], ':');
244+
245+
// Can add more native mongo type casts here.
246+
$value = match (true) {
247+
$castType === 'decimal' => $this->fromDecimal($value, $castOptions),
248+
default => $value,
249+
};
243250
}
244251

245252
// Convert _id to ObjectID.
@@ -279,6 +286,19 @@ protected function asDecimal($value, $decimals)
279286
return parent::asDecimal($value, $decimals);
280287
}
281288

289+
/**
290+
* Change to mongo native for decimal cast.
291+
*
292+
* @param mixed $value
293+
* @param int $decimals
294+
*
295+
* @return Decimal128
296+
*/
297+
protected function fromDecimal($value, $decimals)
298+
{
299+
return new Decimal128($this->asDecimal($value, $decimals));
300+
}
301+
282302
/** @inheritdoc */
283303
protected function castAttribute($key, $value)
284304
{

0 commit comments

Comments
 (0)