John Davidson

php - Laravel format_number eloquent

0 comments
Message:


I am creating a REST API using Laravel and this is a simply version of my Product Eloquent model:


- id
- name
- price (float)

These are examples of prices: 37.27 1926.45 293.


As per Laravel Accessor doc i created this function to add a new attribute to Product:


public function getMagicPriceAttribute($magic)
{
return round($magic * $this->price, 2);
}

To give users a better experience i need to format price as 37,27 1.926,45 293.


So i created:


public function getPriceAttribute($price)
{
return number_format($price);
}

The price is now formatted as needed but given number_format returns a string, getMagicPriceAttribute is not working correctly and throws errors.


Is there a better approach to handle this?



My Answer:
price, 2);_}_This function will add a new attribute called "magic_price" to the Product model, which will be the result of multiplying the "price" attribute by the "magic" parameter and rounding it to 2 decimal places.

Rate this post

5 of 5 based on 7690 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us