Ahmad Badpey
Ahmad Badpey

Reputation: 6612

automatically currency rate conversion in laravel models

I have a Product model included sale_price , purchase_price.this fields holds values as IRR (Iranian rial) currency, means that when an operator user is saving a product ,specifies Sale and Purchase prices in IRR currency in default.

Now in many situations I want to show a list of all products along with their prices that default is same currency that I stored in DB.

Then I want User can switch to another currency(for example via a combo box) and page refreshed and same list of products shown with new selected currency .

I have checked some currency exchange rate packages like laravel-swap and laravel-currency but I did not find any capability to do what I want.

Seems that one approach is define an accessor for each financial fields that uses methods of one of the mentioned packages. but it's Time-consuming if there are many fields.

On the Other hand when a user uses a currency Opposite of Default then we must to define a mutator to convert it and save in DB.

I am confused which approach should be used and what is best and common way.

Upvotes: 1

Views: 2017

Answers (1)

ahmad
ahmad

Reputation: 2729

Nothing is automatic, You'll have to do it yourself.

Make a table & put the exchange rates in there

exchange_rates
------------
currency_code        exchange_rate      Default
IRR                  1                  Yes
USD                  0.000028           No

Then it's just a matter of multiplication when displaying the prices, You can make your own helper functions to do that or a formatter or whatever. You can then either change the exchange rates manually once per day or use an API to pull-in the exchange rate & create something like an artisan console command to do the job.

Upvotes: 1

Related Questions