Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding currency picker to laravel

Tags:

php

laravel

I want to have a drop-down in my navbar where I can select a currency and all the prices in my app convert to selected currency, I know I should use middle-ware for this matter but I don't know how to begin. I am using Fixer with laravel-swap as a package for exchange rates.

What I've done

I have made a middleware named it Currancy and it's content:

<?php

namespace App\Http\Middleware;

use Closure;
use Swap\Swap;
use Swap\Builder;

class Currancy
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Session::has('appcurrency') AND array_key_exists(Session::get('appcurrency'), Config::get('currencies'))) {
            $currency = Session::get('appcurrency'); 
            App::setLocale($currency);
        }
        else {
          App::setLocale(Config::get('app.currency'));
        }
        return $next($request);
    }
}

I also made a currencies.php in config folder:

<?php

return [
  'IDR' => [
      'name' => 'Indunesian Rupiah',
  ],
  'USD' => [
      'name' => 'U.S Dollar',
  ],
  'EUR' => [
      'name' => 'Euro',
  ],
];

I also added this to my config\app.php

'currency' => 'IDR',

in that case my default currency is IDR unless user select others.

PS: for my middleware and config file I've got the idea of language translation and I don't have an idea how to join it to SWAP package in order to work! :\

Questions

  1. Is the way I try to handle currencies correct way?
  2. What else should I do for the next step?

thanks.

like image 357
mafortis Avatar asked May 19 '18 05:05

mafortis


1 Answers

App::setLocale() is for language purpose.

Do not use a middle-ware to set a session default value. It will bloat your route file. Use the view composer for output. https://laravel.com/docs/4.2/responses#view-composers

Run this command if you do not have a view composer provider:

php artisan make:provider ComposerServiceProvider

In "app/Providers/ComposerServiceProvider.php", in the "boot()" method

public function boot()
{
    View::composer(array('header','footer'), function($view)
    {
        if (!currentCurrency()) {
            setCurrency(config('app.currency'));
        }
        $view->with('currencies', config('currencies');
    });
}

Define some helper functions. To load a helper, use the autoload feature of the composer. In "composer.json" in the "autoload" attribute tight, after the "psr-4" one: it will load "app/Support/helpers.php" as an example.

    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Support/helpers.php"
    ]

After changing "composer.json", regenerate the autoload file with the command:

composer dump-autoload

In "app/Support/helpers.php" (create it) add these functions:

<?php

if (!function_exists('currentCurrency')) {
    /**
     * @return string
     */
    function currentCurrency(){
        if (Session::has('appcurrency') AND array_key_exists(Session::get('appcurrency'), config('currencies'))) {
            return Session::get('appcurrency');
        }
        return '';
    }
}

if (!function_exists('setCurrency')) {
    /**
     * @param string $currency
     * @return void
     * @throws \Exception
     */
    function setCurrency($currency){
        if (array_key_exists($currency, config('currencies'))) {
            Session::set('appcurrency', $currency);
        } else {
            throw new \Exception('not a valid currency');
        }
    }
}

If you need to set the locale to one of the currency, change the "setCurrency" method, since you only need to set the locale once per session.

/**
* @param string $currency
* @return void
* @throws \Exception
*/
function setCurrency($currency){
    if (array_key_exists($currency, config('currencies'))) {
        Session::set('appcurrency', $currency);
        App::setLocale($currency);
    } else {
        throw new \Exception('not a valid currency');
    }
}
like image 60
N69S Avatar answered Sep 22 '22 23:09

N69S