DEV Community

Cover image for Dealing with currency in Laravel
Salih for Kodeas

Posted on

Dealing with currency in Laravel

Most applications have to deal with currencies in some way or another and unfortunately it isn't always straightforward due to database limitations.

Among a few different solutions to how to store currency in the database my choice always is storing it in cents as an integer. (if you prefer another way turn around now)

Storing in cents solves many of our problems like dealing with floats and such, however, creates a new challenge, remembering what state your variables are in. The amount of times I would by mistake store a currency in USD format instead or converted cents to cents again is way too damn high. Also converting constantly back and forth gets quite old quickly and don't we all hate writing the same thing over and over again?
Let me demonstrate what I am talking about.

$currency = 1;
$currencyInCents = $currency * 100;
$someFeeRate = 0.12;

$currencyInCentsWithFee = $currencyInCents * $someFeeRate;

$model = Model::create([
  'amount' => $currencyInCentsWithFee

// $model->amount - 
//I already lost what format this was in may be I have a bad memory

return response()->json([
  'currency' => '$'.number_format($model->amount / 100, 2)
Enter fullscreen mode Exit fullscreen mode

Did you realise how many times I had to write "inCents" within my variables?
Of course I am exaggerating a little bit with this example but once there more levels of calculations things get worse and worse if you have been there, you know.

There is also a good chance that the next developer within the project is going to do something completely different to what I just did.

As a solution we came up with a simple package for currency:

$currency = Currency::fromUsd(1);

$someFeeRate = 0.12;

$currencyWithFee = Currency::fromCents($currency->inCents() * $someFeeRate);

//model has currency as a cast of Currency::class
$model = Model::create([
  'amount' => $currencyWithFee

//$model->amount - 
//this is now an instance of Currency::class so it is in whatever format you wish

return response()->json([
  'currency' => $model->amount->toReadable('$')
Enter fullscreen mode Exit fullscreen mode

The currency class is used as a cast to standardise currency operations in your entire app, regardless of who is the developer writing it. Your currency will always be stored in cents and you will never forget what state your currency was during your operations.

I also appreciate you might be sceptical of adding a package for something so simple therefore, I also wrote about how it was made so you can also create one of your own.

There it is, nice and quick solution to most of your currency issues while using Laravel.

Please feel free to contribute to the package if you have any additions and show some ❤️ with a like if this helped you.

Top comments (0)