laravel-forex maintained by elegantly
Laravel Forex
Laravel Forex is a simple and flexible package for retrieving the latest and historical foreign exchange rates in your Laravel application.
By default, it uses the free tier from exchangerate-api.com, but you can easily configure it to use any other Forex provider.
Installation
Install via Composer:
composer require elegantly/laravel-forex
Publish the configuration file:
php artisan vendor:publish --tag="forex-config"
Configuration
Here’s the default configuration that will be published to config/forex.php:
use Elegantly\Forex\Integrations\ExchangeRateApiFree\ExchangeRateApiFreeConnector;
return [
'cache' => [
'enabled' => true,
'driver' => env('FOREX_CACHE_DRIVER', env('CACHE_STORE', env('CACHE_DRIVER', 'file'))),
'expiry_seconds' => 86_400, // 1 day
],
'rate_limit' => [
'enabled' => false,
'driver' => env('FOREX_RATE_LIMIT_DRIVER', env('CACHE_STORE', env('CACHE_DRIVER', 'file'))),
'every_seconds' => 3_600, // 1 hour
],
'client' => ExchangeRateApiFreeConnector::class,
'clients' => [
'exchange-rate-api' => [
'token' => env('EXCHANGE_RATE_API_TOKEN'),
],
],
];
Usage
Get Latest Rates
use Elegantly\Forex\Facades\Forex;
$rates = Forex::latest('USD');
$usdToEur = $rates['EUR'];
Get Historical Rates
use Carbon\Carbon;
use Elegantly\Forex\Facades\Forex;
$rates = Forex::rates(Carbon::create(2022, 4, 25), 'USD');
$usdToEur = $rates['EUR'];
Convert Money Between Currencies
You can easily convert a Money instance from one currency to another using the Forex::convert() method.
This method ensures high-precision conversions by leveraging the brick/money PHP library.
use Elegantly\Forex\Facades\Forex;
use Brick\Money\Money;
$convertedMoney = Forex::convert(
money: Money::of(100, 'USD'),
currency: 'EUR',
);
$convertedMoney->__toString(); // (EUR) 88.84
Note: The returned value is a Money object representing the amount in the target currency.
Testing
Run the test suite with:
composer test
Changelog
See the CHANGELOG for details on recent updates.
Contributing
Contributions are welcome! Please read the CONTRIBUTING guide for details.
Security
If you discover any security-related issues, please refer to our security policy.
Credits
License
This package is open-source software licensed under the MIT license.