This beginner guide walks you through the process of creating a CurrencyConverter class in Laravel. This class leverages the ExchangeRate API to perform currency conversions, retrieve exchange rates, and more other useful functionalities. By the end of this guide, you will have a solid foundation for integrating currency conversion features into your Laravel applications.
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
class CurrencyConverter {
private Client $client;
private string $accessKey;
public function __construct($accessKey) {
$this->client = new Client([
"base_uri" => "http://api.exchangerate.host"
]);
$this->accessKey = $accessKey;
}
/**
* Get the most recent exchange rate data
* @param array $data
* @return mixed
*/
public function live(array $data = []): mixed
{
return $this->apiRequest("live", $data);
}
/**
* Convert one currency to another
* @param $from
* @param $to
* @param $amount
* @param array $data
* @return mixed
*/
public function convert($from, $to, $amount, array $data = []): mixed
{
$data += ["from" => $from, "to" => $to, "amount" => $amount];
return $this->apiRequest("convert", $data);
}
/**
* Get historical rates for a specific day
* @param $date
* @param array $data
* @return mixed
*/
public function historical($date, array $data = []): mixed
{
$data += ["date" => $date];
return $this->apiRequest("historical", $data);
}
/**
* Request exchange rates for a specific period of time
* @param $start_date (format YYYY-MM-DD)
* @param $end_date (format YYYY-MM-DD)
* @param array $data
* @return mixed
*/
public function timeframe($start_date, $end_date, array $data = []): mixed
{
$data += ["start_date" => $start_date, "end_date" => $end_date];
return $this->apiRequest("timeframe", $data);
}
/**
* Request any currency's change parameters (margin, percentage)
* @param $currencies
* @param array $data
* @return mixed
*/
public function change($currencies, array $data = []): mixed
{
$data += ["currencies" => $currencies];
return $this->apiRequest("change", $data);
}
/**
* Get a list of all supported currencies by the API
* @param array $data
* @return mixed
*/
public function list(array $data = []): mixed
{
return $this->apiRequest("list", $data);
}
private function apiRequest($path, $data) {
$query = http_build_query(["access_key" => $this->accessKey] + $data);
$cacheKey = '$path' . $query;
$cacheDuration = now()->addMinutes(30); // Set the cache duration to 30 minutes
try {
return Cache::remember($cacheKey, $cacheDuration, function () use ($query, $path, $data) {
$response = $this->client->get("/$path?$query");
return json_decode($response->getBody());
});
} catch(GuzzleException) {
// Handle the exception (e.g., log, throw a custom exception, etc.)
// Example: throw new ApiRequestException("Failed to make API request.", 0, $e);
return null; // or provide a default fallback value
}
}
}
To improve performance and reduce unnecessary API calls, the class incorporates caching using Laravel’s Cache facade. It stores API responses in the cache, associating them with a unique cache key generated based on the API endpoint and the provided request parameters.
When a conversion request is made, the class first checks if the requested data is available in the cache. If found, it retrieves the cached response. Otherwise, it proceeds to make an API request, stores the response in the cache, and returns the data.
Example of using the live method (retrieves the most recent currency exchange rates from the API):
// Be sure to provide your own API access key.
// Note we use the Free Subscription Plan for this tutorial
$converter = new CurrencyConverter("5edf6c440cdaa42336d949*****");
return $converter->live();
Example of using the convert method (convert a specified amount from one currency to another):
// Be sure to provide your own API access key.
// Note we use the Free Subscription Plan for this tutorial
$converter = new CurrencyConverter("5edf6c440cdaa42336d949*****");
return $converter->convert('USD', 'ZMW', 100);
Example of using the historical method (gets historical rates for a specific date):
// Be sure to provide your own API access key.
// Note we use the Free Subscription Plan for this tutorial
$converter = new CurrencyConverter("5edf6c440cdaa42336d9491c9aa37f0c");
return $converter->historical('2023-06-01');
Example of using the timeframe method (retrieves exchange rates for a specific period of time):
// Be sure to provide your own API access key.
// Note we use the Free Subscription Plan for this tutorial
$converter = new CurrencyConverter("5edf6c440cdaa42336d949*****");
return $converter->timeframe('2023-06-01', '2023-06-07');
Example of using the change method (requests any currency’s change parameters (margin, percentage)):
// Be sure to provide your own API access key.
// Note we use the Free Subscription Plan for this tutorial
$converter = new CurrencyConverter("5edf6c440cdaa42336d949*****");
return $converter->change("USD,EUR");
Example of using the list method (get a list of all supported currencies by the API):
// Be sure to provide your own API access key.
// Note we use the Free Subscription Plan for this tutorial
$converter = new CurrencyConverter("5edf6c440cdaa42336d949*****");
return $converter->list();
That was all I had to share with you guys. If you found this code informative and would love to see more, don’t forget to subscribe to our newsletter! 😊