Laravel currency is a Laravel package that gives the historical, latest currency rate and converts from one currency to another. It also provides crypto exchange rates.
This is possible with the help of exchangerate.host
In this shot, we will focus on getting the latest rate of currencies. This will be helpful when you want to display to your website visitors the latest currency rate for informational purposes.
To integrate the currency library, we must have the following:
PHP >= 7.2
Laravel >= 6.0
guzzlehttp >= 6.0
To install the package, we run the command below.
composer require amrshawky/laravel-currency
Import the class below into your controller where you want to implement it.
use AmrShawky\LaravelCurrency\Facade\Currency;
Currency::rates()
->latest()
->get();
The output of the code above is an array of currencies and their exchange rates, like this:
['USD' => 1.215707, 'GBP'=> 0.8,....]
The code example above chains two methods, the rates()
and the latest()
. These methods ensure that you get the latest currency rates. The get()
method returns the result as an array
which you will iterate through, or null
, if it fails.
You can limit the currency you want to be checking. Let’s say you want just three currency pairs. You can chain the symbols(['USD', 'EUR', 'EGP'])
method just after the latest()
method.
To give a practical example, we will create a controller name CurrencyController.php
like so:
Type php artisan make:controller CurrencyController
on your command line.
You can find your new controller in the app/Http/Controllers/
directory as CurrencyController.php
.
<?phpnamespace App\Http\Controllers;use AmrShawky\LaravelCurrency\Facade\Currency;use Illuminate\Http\Request;class CurrencyController extends Controller {public function GetLatestCurrency(){$rate = Currency::rates()->latest()->base('USD')// sets base currency default is 'EUR'->get();// array output will be like this ['USD' => 1.215707, ...]return view('blog',compact('rate'));}}
In the code example above, GetLatestCurrency()
will return the $rate
array that contains the latest currency rate. With this, you will then loop through in your blog
blade file to get the individual currency rate with USD as the base currency.