Trusted answers to developer questions

How to get the latest currency rate with laravel-currency

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

What is Laravel currency?

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 APIApplication Programming Interface, which is free and does not need an API key.

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.

Integrating the currency library

To integrate the currency library, we must have the following:

  • PHP >= 7.2

  • Laravel >= 6.0

  • guzzlehttp >= 6.0

Installation

To install the package, we run the command below.


composer require amrshawky/laravel-currency

Getting the latest currency rate

Import the class below into your controller where you want to implement it.


use AmrShawky\LaravelCurrency\Facade\Currency;

Currency::rates()
        ->latest()
        ->get();

Output

The output of the code above is an array of currencies and their exchange rates, like this:


['USD' =>  1.215707, 'GBP'=> 0.8,....]

Explanation

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.

Code

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.

<?php
namespace 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'));
}
}

Explanation

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.

RELATED TAGS

laravel

CONTRIBUTOR

Chinweuba Elijah Azubuike
Did you find this helpful?