Laravel 7 — Showing localised prices with currency conversion

Zeba Rahman
fabcoding
Published in
3 min readOct 2, 2020

If you’re creating an application that supports international purchases, you would definitely want to show the prices in the user’s localised currency and formatting (since different countries have different formats). Doing this cleanly and efficiently would be a challenge. So we will be using 2 packages by Daniel Stainback that will make this easy and efficient.

Part A — Installation and Configuration

Install the packages

We will install 2 packages. The torann/currency package for currency conversion and formatting, and the torann/geoip package for detecting the local currency of the user.

composer require torann/currency
composer require torann/geoip

Let us publish the config and migration files so that we can make changes.

php artisan vendor:publish --provider="Torann\Currency\CurrencyServiceProvider" --tag=config
php artisan vendor:publish --provider="Torann\Currency\CurrencyServiceProvider" --tag=migrations
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config

Then run the migrate command to build the tables.

php artisan migrate

Configure Currency

Add the supported currencies to our project database

php artisan currency:manage add usd,gbp,cad,aud,sek,inr,cny,eur

Data for exhcange rates

We will use OpenExchangeRates.org for getting the exchange rate data. Create a free account, Get the API key (App ID) and add it to our project environment variables.

.env

OPEN_EXCHANGE_RATE_KEY=<API KEY>

and then replace key attribute in the config file

config/currency.php

'api_key' => env('OPEN_EXCHANGE_RATE_KEY'),

Update the exchange rates

For updating the exchange rate to the latest data, run the command

php artisan currency:update -o

Imprtant Note: You will need to run this command on regular intervals, for example, once every day so that the rates in your database are up to date.

For this you can use a cron job.

Set default currency

Set the default currency in the following file, which will be used when no currency is chosen.

config/currency.php

'default' => 'USD',

Alternatively, you can set default currency in environment variables and just reference it here, this way it can be modified easily, later on.

.env

DEFAULT_CURRENCY=USD

config/currency.php

'default' => env('DEFAULT_CURRENCY', 'USD'),

Configure GeoIP

The library uses cache tags but this is not supported on Laravel installations that use the file or database cache driver, so let us remove it.

config/geoip.php file

'cache_tags' => false,

for locating IPs we will use IP-API. They allow up to 150 requests per minute, for free, without an API key.

Later if you want to handle more requests, you will subscribe to their plan and add the API key:

.env

IPAPI_KEY=<KEY>

Part B — Setting a default currency for the current user’s current session

The library provides a middleware CurrencyMiddleware that will allow setting the local currency of the current user for the session.

So let’s add this middleware to our project

app/Http/Kernel.php

Include the CurrencyMiddleware class AFTER the StartSession class within the web array of $middlewareGroups :

protected $middlewareGroups = [
'web' => [
...
\Illuminate\Session\Middleware\StartSession::class,
\Torann\Currency\Middleware\CurrencyMiddleware::class,
...
],
];

Using GeoIP, we will detect the local currency of the current location of the user, and attach this to the user’s current session. The user’s session may change so its ideal to put this logic in a middleware. So let us create a new middleware

php artisan make:middleware UserCurrencyMiddleware

Go to the file that was just created and add the function

app/Http/Middleware/UserCurrencyMiddleware.php

public function handle(Request $request, Closure $next) {
if (! $request->get('currency') && ! $request->getSession()->get('currency')) {
$clientIP = $request->getClientIp();
$localCurrency = geoip($clientIP)->getAttribute('currency');
$request->getSession()->put([
'currency' => $localCurrency,
]);
}
return $next($request);
}

As you have can see from the code, apart from automatic detection, this also enables you to send ‘currency’ attribute in any request to set the user’s default currency to a custom value.

We need this to run after StartSession and just before the CurrencyMiddleware. So again, modify the kernel file.

app/Kernel.php

Include the CurrencyMiddleware class AFTER the StartSession class within the web array of $middlewareGroups :

protected $middlewareGroups = [
'web' => [
...
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\UserCurrencyMiddleware::class,
\Torann\Currency\Middleware\CurrencyMiddleware::class,
...
],
];

That’s it! Now you can use the methods anywhere in your code.

To get user’s currency:

$currency = currency()->getUserCurrency();

To format a price, stored in a given currency (say, USD), converted to user’s currency and also formatted to it.

$str = currency(5.99, 'USD', currency()->getUserCurrency());

I hope this was helpful. If you have any questions, feel free to comment.

Also published at Fabcoding.

--

--