Reputation: 123
If I have a column like this 'price' as decimal, when I get this value from Database, it returns a string instead of decimal or float. How can I fix this?
Upvotes: 2
Views: 2060
Reputation: 31
in the migration make sure that the column is decimal
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->decimal('price');
});
}
then cast it in the model:
protected $casts = [
'price' => 'decimal:2',
];
now you can retrieve it in the controller or in the frontend
$price = Product->price; --> in the Controller
{{ $product->price }} --> in the view
Upvotes: 3
Reputation: 280
You can just do this before showing;
$price = (float)$product->price;
Or you can make a function, it will work.
Upvotes: 3
Reputation: 194
you can solve it in the whole project by casting in model
protected $casts = ['column_name' => 'type'];
example:
protected $casts = ['price' => 'float'];
documentation link: click here
Upvotes: 1