Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahmadbadpey's avatar

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.

0 likes
4 replies
bobbybouwmann's avatar
Level 88

You would indeed use an accessor to get the correct value of the price. In this case your accessor needs to understand how to convert the price to another currency. You have multiple options here. One of the packages is a good idea, but indeed they take some time. Another option would be using a database where you keep the current currency. You can update that once an hour or once a day and work with that value. That might be quicker already!

The mutator works the other way around. You can for example store a product with a currency of euro and than convert it to IIR before storing it. Just like the assessor you can use the same approach, the package or a lookup table!

Let me know if that helped you!

1 like
ahmadbadpey's avatar

@bobbybouwmann , thanks for your help. your explanation was helpful. but another issue that I have is that in my models there are many financial field. in this case do I add one accesssor for each of them ?

I was searched for l package that mange this case automatically.

bobbybouwmann's avatar

I don't think there is a package for that. I think an accessor for each field is fine. You can make a helper method that you can reuse in each accessor of course ;)

This is also the perfect opportunity to create your own package ;)

Anyway, merry Christmas

1 like

Please or to participate in this conversation.