I’m trying to implement currency converter in laravel using
torann/currency package
https://lyften.com/projects/laravel-currency/doc/
installed this package
composer require torann/currency
publish the package
php artisan vendor:publish --provider="TorannCurrencyCurrencyServiceProvider" --tag=config
php artisan vendor:publish --provider="TorannCurrencyCurrencyServiceProvider" --tag=migrations
then run migration
php artisan migrate
i have to convert from usd to sek and vice versa default currency will be usd
php artisan currency:manage add usd,sek
used OpenExchangeRates.org for getting the exchange rate data
config/currency.php
'api_key' => env('OPEN_EXCHANGE_RATE_KEY'),
For updating the exchange rate in the db
php artisan currency:update -o
Set default currency to USD in config/currency.php
'default' => env('DEFAULT_CURRENCY', 'USD'),
added CurrencyMiddleware
protected $middlewareGroups = [
'web' => [
...
IlluminateSessionMiddlewareStartSession::class,
TorannCurrencyMiddlewareCurrencyMiddleware::class,
...
],
];
created UserCurrencyMiddleware.php
public function handle(Request $request, Closure $next)
{
if (! $request->get('currency') && ! $request->getSession()->get('currency')) {
$request->getSession()->put([
'currency' => 'SEK',
]);
}
return $next($request);
}
on my blade.php
currency is converting
{{ currency(5.99, 'USD', currency()->getUserCurrency()); }}
but i want it to convert it based on dropdown selection if user changes to USD it should be USD and KR it should be converted to kr.
<select class="form-control">
<option value="USD">USD</option>
<option value="KR">Kr</option>
</select>
current db structure:
Any solution Thanks
2
Answers
create a simple API endpoint that receives the amount, and currency, and returns a response with the converted amount then in select input onChange event call that API with Ajax
here is sample code
if you want to update the current selected currency for the user, you need to make a post request with the selected currency and update your session.
and in you blade file create a form, (don’t forget to declare the route):