PHPackages                             rnr1721/currency-service - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rnr1721/currency-service

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

rnr1721/currency-service
========================

Laravel Currency Service with currency library, formatting and conversion

1.0.3(1y ago)011MITPHPPHP ^8.1

Since Jan 30Pushed 1y ago1 watchersCompare

[ Source](https://github.com/rnr1721/currency-service)[ Packagist](https://packagist.org/packages/rnr1721/currency-service)[ Docs](https://github.com/rnr1721/currency-service)[ RSS](/packages/rnr1721-currency-service/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (8)Versions (6)Used By (0)

Laravel Currency Service
========================

[](#laravel-currency-service)

Looking for a powerful and easy-to-use currency management tool for your Laravel application? Our Laravel Currency Service offers everything you need to manage currencies, handle conversions, track exchange rates, and store historical data — all in one seamless package.

Features
--------

[](#features)

- Currency conversion with configurable precision and rounding modes
- Customizable currency formatting (position, separators, decimals)
- Exchange rate management with historical tracking
- Multiple rate providers support (includes TestRateProvider and OpenExchangeRates)
- Advanced caching system
- Historical rates analysis
- SOLID architecture principles
- Comprehensive test coverage
- Full Laravel integration

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.0 or higher
- Composer

Installation
------------

[](#installation)

```
composer require rnr1721/currency-service

# Publish configuration file
php artisan vendor:publish --tag=currency-config

# Run migrations (migrations will run directly from the package)
php artisan migrate

# Optionally, if you want to customize migrations:
php artisan vendor:publish --tag=currency-migrations
```

Configuration (If you want to make automatic rates synchronization etc)
-----------------------------------------------------------------------

[](#configuration-if-you-want-to-make-automatic-rates-synchronization-etc)

The configuration file will be published to Config/currency.php:

```
return [
    'cache_ttl' => 3600,
    'providers' => [
        'default' => OpenExchangeRatesProvider::class, // You can write own if you need rates sync
    ],
    'formatting' => [
        'decimals' => 2,
        'decimal_separator' => '.',
        'thousands_separator' => ',',
        'show_currency_code' => true,
        'currency_position' => 'after',
    ],
    'conversion' => [
        'rounding_precision' => 2,
        'rounding_mode' => PHP_ROUND_HALF_UP,
    ]
];
```

Currency Management
-------------------

[](#currency-management)

### Initial Setup

[](#initial-setup)

1. First, create your base currencies. At minimum, you should define a default currency:

```
use rnr1721\CurrencyService\Facades\Currency;
use rnr1721\CurrencyService\DTO\CurrencyDTO;
use rnr1721\CurrencyService\Repositories\CurrencyRepository;

// Get repository instance
$repository = app(CurrencyRepository::class);

// Create default currency
$repository->save(new CurrencyDTO(
    code: 'USD',
    name: 'United States Dollar',
    isDefault: true
));

// Add more currencies
$repository->save(new CurrencyDTO(
    code: 'EUR',
    name: 'Euro',
    isDefault: false
));

$repository->save(new CurrencyDTO(
    code: 'GBP',
    name: 'British Pound',
    isDefault: false
));
```

### Creating or Updating Currencies

[](#creating-or-updating-currencies)

The save() method handles both creation and updates based on currency code:

```
// This will create a new currency if JPY doesn't exist
// or update it if it already exists
$repository->save(new CurrencyDTO(
    code: 'JPY',
    name: 'Japanese Yen',
    isDefault: false
));
```

### Retrieving Currencies

[](#retrieving-currencies)

```
// Get all currencies
$currencies = Currency::getAllCurrencies();

// Get all currencies with actual rates to default currency (except default currency)
$currencies = Currency::getAllCurrenciesWithRates();

// Get specific currency
$usd = $repository->findByCode('USD');

// Get default currency
$default = Currency::getDefaultCurrency();
```

Or, available DI way

```
// You can inject CurrencyServiceInterface in standard Laravel way
use rnr1721\CurrencyService\Contracts\CurrencyServiceInterface;

$currencies = $currencyService->getAllCurrencies();
$currencyRates = $currencyService->getAllCurrenciesWithRates();
```

### Manual Rate Management

[](#manual-rate-management)

If you're not using an automatic rate provider, you can manually manage rates:

```
// You can inject CurrencyServiceInterface in standard Laravel way
use rnr1721\CurrencyService\Contracts\CurrencyServiceInterface;

// Will set USD rate to default currency as 42.5
$service->saveDefaultRate('USD', 42.5);
```

Or more custom way:

```
// You can inject CurrencyRepositoryInterface in standard Laravel way
use rnr1721\CurrencyService\Contracts\CurrencyRepositoryInterface;
use rnr1721\CurrencyService\DTO\CurrencyRateDTO;

// Set rate from USD to EUR
$repository->saveRate(new CurrencyRateDTO(
    fromCurrency: 'USD',
    toCurrency: 'EUR',
    rate: 0.92,
    updatedAt: new DateTime()
));

// Rates are automatically inversed when needed
// so you don't need to save both USD->EUR and EUR->USD
```

Deleting the currencies
-----------------------

[](#deleting-the-currencies)

```
// You can inject CurrencyRepositoryInterface in standard Laravel way
use rnr1721\CurrencyService\Contracts\CurrencyRepositoryInterface;

// Will try to delete EUR currency with related rate history
$repository->deleteCurrency('EUR');
```

Currency Administration Tips
----------------------------

[](#currency-administration-tips)

### Initial Setup

[](#initial-setup-1)

- Always set up a default currency first
- Use standardized 3-letter ISO currency codes
- Consider implementing a seeder for basic currencies

### Rate Management

[](#rate-management)

- Update rates regularly if managing manually
- Consider implementing a schedule for rate updates
- Keep historical rates for reporting

### Best Practices

[](#best-practices)

- Validate currency codes before saving
- Handle rate update failures gracefully
- Consider implementing rate validity periods
- Add logging for important currency operations

Basic Usage
-----------

[](#basic-usage)

```
use rnr1721\CurrencyService\Facades\Currency;

// Currency conversion
$euros = Currency::convert(100, 'USD', 'EUR');

// Convert 100 USD to default currency
$amount = Currency::convert(100, 'USD');

// Format amount
$formatted = Currency::format(99.99, 'USD'); // "99.99 USD"

// Format amount with default currency
$formatted = Currency::format(99.99);

// Get current exchange rate
$rate = Currency::getCurrencyRate('USD', 'EUR');

// Get current exchange rate (to default currenct)
$rate = Currency::getCurrencyRate('USD');

// Set default currency
Currency::setDefaultCurrency('EUR');

// Update exchange rates
Currency::updateRates();

// Get all currencies
Currency::getAllCurrencies();

// Get current default currency
Currency::getDefaultCurrency();
```

of if you prefer Di, you can inject it and use:

```
namespace App\Http\Controllers;

use rnr1721\CurrencyService\Contracts\CurrencyServiceInterface;

class CurrencyController extends Controller
{
    private CurrencyServiceInterface $currencyService;

    public function __construct(CurrencyServiceInterface $currencyService)
    {
        $this->currencyService = $currencyService;
    }

    public function convert()
    {
        $amount = 100;
        $fromCurrency = 'USD';
        $toCurrency = 'EUR';

        $convertedAmount = $this->currencyService->convert($amount, $fromCurrency, $toCurrency);

        return response()->json([
            'converted_amount' => $convertedAmount
        ]);
    }
}
```

Advanced Usage
--------------

[](#advanced-usage)

```
use rnr1721\CurrencyService\DTO\FormatSettingsDTO;
use rnr1721\CurrencyService\DTO\ConversionSettingsDTO;

// Custom formatting
use rnr1721\CurrencyService\DTO\FormatSettingsDTO;

$formatted = Currency::format(
    amount: 99.99,
    currencyCode: 'USD',
    settings: new FormatSettingsDTO(
        decimals: 2,
        decimalSeparator: ',',
        thousandsSeparator: ' ',
        showCurrencyCode: true,
        currencyPosition: 'before'
    )
); // "USD 99,99"

// Custom conversion settings
$converted = Currency::convert(
    amount: 100,
    from: 'USD',
    to: 'EUR',
    settings: new ConversionSettingsDTO(
        roundingPrecision: 3,
        roundingMode: PHP_ROUND_HALF_DOWN
    )
);
```

### Working with Exchange Rate History

[](#working-with-exchange-rate-history)

```
use rnr1721\CurrencyService\Facades\Currency;
use DateTime;

// Get paginated history
$history = app(CurrencyRateHistoryRepositoryInterface::class)->getPaginatedHistory(
    fromCurrency: 'USD',
    toCurrency: 'EUR',
    startDate: new DateTime('-30 days'),
    perPage: 20
);

// Get statistics
$stats = app(CurrencyRateHistoryRepositoryInterface::class)->getHistoryStats(
    fromCurrency: 'USD',
    toCurrency: 'EUR',
    startDate: new DateTime('-7 days'),
    endDate: new DateTime()
);
```

### Custom Rate Providers

[](#custom-rate-providers)

You can create your own rate providers by implementing CurrencyRateProviderInterface:

```
use rnr1721\CurrencyService\Contracts\CurrencyRateProviderInterface;

class CustomRateProvider implements CurrencyRateProviderInterface
{
    public function getRates(string $baseCurrency): array
    {
        // Implement your rate fetching logic
        return [
            'EUR' => 0.92,
            'GBP' => 0.79,
            // ...
        ];
    }
}
```

Then register it in your configuration:

```
'providers' => [
    'default' => CustomRateProvider::class,
],
```

Exception Handling
------------------

[](#exception-handling)

The service throws the following exceptions:

- CurrencyNotFoundException - When a requested currency doesn't exist
- CurrencyRateNotFoundException - When an exchange rate is not available
- CurrencyProviderException - When there's an error fetching rates
- NoCurrencyException - When no default currency is set

Testing
-------

[](#testing)

```
composer install
composer test
composer analyse
composer check-style
```

License
-------

[](#license)

MIT License. See the LICENSE file for details.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance44

Moderate activity, may be stable

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

4

Last Release

444d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b056f4160d8f9302378726a35860b42bfa67c29760bb55fcacddfde2bfa6f6ac?d=identicon)[rnr1721](/maintainers/rnr1721)

---

Top Contributors

[![rnr1721](https://avatars.githubusercontent.com/u/122087344?v=4)](https://github.com/rnr1721 "rnr1721 (7 commits)")

---

Tags

laravelmoneycurrencyconversionformattingexchange

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rnr1721-currency-service/health.svg)

```
[![Health](https://phpackages.com/badges/rnr1721-currency-service/health.svg)](https://phpackages.com/packages/rnr1721-currency-service)
```

###  Alternatives

[grumpydictator/firefly-iii

Firefly III: a personal finances manager.

22.8k69.3k](/packages/grumpydictator-firefly-iii)[florianv/laravel-swap

Currency exchange rates library for Laravel and Lumen

3342.0M2](/packages/florianv-laravel-swap)[firefly-iii/data-importer

Firefly III Data Import Tool.

7545.8k](/packages/firefly-iii-data-importer)[torann/currency

This provides Laravel with currency functions such as currency formatting and conversion using up-to-date exchange rates.

4081.1M6](/packages/torann-currency)[danielme85/laravel-cconverter

Laravel 5 plug-in for currency conversion

42101.1k](/packages/danielme85-laravel-cconverter)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
