Laravel Eloquent attribute casting doesn't work

Viewed 581

I have a field in my database that stores a decimal value. It's defined in my database migration as such:

$table->decimal('buy_amount', 16, 8)->default(0);

Now reading from the database using Laravel Eloquent it returns a string value instead. According to the documentation, I tried casting it in the model file using the $casts array however it makes no difference. It's worth mentioning that every other cast works fine except for decimals.

protected $casts = [
    'buy_amount' => 'decimal:8',
];

This is the result I get:

enter image description here

What am I missing?

1 Answers

This happens because PHP doesn't have a decimal type, so the value is converted to a string (see this Laracasts post)

When casting to a decimal, the asDecimal(...) function in Illuminate\Database\Eloquent\Concerns\HasAttributes is called; this function uses the native PHP function number_format, which returns a string.

Related