2

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
  • Store price as int. Commented Jan 16, 2021 at 0:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.