skip to Main Content

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:

enter image description here

Any solution Thanks

2

Answers


  1. 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

    controller:
    
    public function convertCurrency(Request $request){
    $amount = currency($request->amount, $request->from , currency()->getUserCurrency());
    
    return response()->json(['amount' => $amount ]);
    }
    
    route:
    Rooute::get("/convert-currency", [SomeController::class,'convertCurrency']);
    
    script:
    $('#select').change(function(){
    $.ajax({
        url: "/api/convert-currency",
        data: { "amount": 20 , "from": $("#select").val() },
        type: "post",
        success: function(data){
           //handle success res
        }
    });
    });
    
    Login or Signup to reply.
  2. 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.

    class CurrencyController extends Controller
    {
      public function __invoke(Request $request)
      {
        $request->validate(['currency' => 'required','exists:currencies,slug']);
        $request->session()->put(['currency' => $request->currency]);
        return response()->json(['currency' => $request->session()->get('currency')]);
      }
    }
    

    and in you blade file create a form, (don’t forget to declare the route):

    <form action="{{route('currency.store')}}" method="POST" id="currency-form">
      @csrf
      <select class="form-control">
        <option value="USD">USD</option>
        <option value="KR">Kr</option>
      </select>
    </form>
    
    <script>
    // assuming you are using JQuery
    $.(`#currency-form`).onChange(function (e) {
      $.post(`{{route('currency.store')}}`, ['currency' => this.value]);
      window.location.reload();
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search