Skip to content

Add exchange rates support with separate table and API integration#145

Open
Haeyzed wants to merge 1 commit intonnjeim:masterfrom
Haeyzed:exchange_rate
Open

Add exchange rates support with separate table and API integration#145
Haeyzed wants to merge 1 commit intonnjeim:masterfrom
Haeyzed:exchange_rate

Conversation

@Haeyzed
Copy link

@Haeyzed Haeyzed commented Jan 3, 2026

Detailed PR Description

Description

This PR implements exchange rates support for the World package, addressing the feature request to add exchange rate functionality. Following the maintainer's guidance, exchange rates are stored in a separate exchange_rates table with a relationship to currencies, where the latest entry is used for computations.

Changes Made

Database

  • ✅ Created exchange_rates table migration with:
    • currency_id (foreign key to currencies)
    • exchange_rate (decimal, 15,6 precision)
    • base_currency (string, defaults to USD)
    • created_at and updated_at timestamps
    • Index on currency_id and created_at for efficient latest rate queries

Models

  • ✅ Created ExchangeRate model with:

    • Relationship to Currency model
    • WorldConnection trait for custom database connection support
    • Proper fillable fields and casts
  • ✅ Updated Currency model:

    • Added exchangeRates() hasMany relationship
    • Updated PHPDoc to include exchangeRates relationship

Services

  • ✅ Created ExchangeRateService class with:
    • Support for multiple API providers (exchangerate-api, Fixer.io, CurrencyLayer, custom)
    • Automatic rate fetching and storage
    • Error handling and logging
    • Base currency support (defaults to USD)

Commands

  • ✅ Created world:update-exchange-rates artisan command:
    • Fetches rates from configured API provider
    • Stores rates in database
    • Provides feedback on success/failure

Configuration

  • ✅ Added exchange rate configuration to config/world.php:
    • Provider selection
    • API key and URL settings
    • Base currency configuration
    • Enable/disable flag

API Integration

  • ✅ Updated Currency IndexAction to support exchangeRates relation
  • ✅ Updated Currency IndexTransformer to return latest exchange rate when requested
  • ✅ Maintains backward compatibility (exchange rates are optional)

Usage

1. Enable Exchange Rates

Add to your .env file:

WORLD_EXCHANGE_RATES_ENABLED=true
WORLD_EXCHANGE_RATE_PROVIDER=exchangerate-api
WORLD_EXCHANGE_RATE_BASE=USD

2. For Free Tier (exchangerate-api.com)

No API key required:

WORLD_EXCHANGE_RATES_ENABLED=true
WORLD_EXCHANGE_RATE_PROVIDER=exchangerate-api

3. For Paid APIs

WORLD_EXCHANGE_RATES_ENABLED=true
WORLD_EXCHANGE_RATE_PROVIDER=fixer
WORLD_EXCHANGE_RATE_API_KEY=your_api_key_here

4. Fetch Exchange Rates

Run the artisan command:

php artisan world:update-exchange-rates

5. Schedule Automatic Updates

In app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->command('world:update-exchange-rates')
             ->daily()
             ->at('02:00');
}

6. Use in Code

use Nnjeim\World\World;

$action = World::currencies([
    'fields' => 'code,name,exchangeRates',
    'filters' => ['code' => 'EUR']
]);

if ($action->success) {
    $currency = $action->data->first();
    $latestRate = $currency['exchangeRates'];
    // Contains: id, exchange_rate, base_currency, created_at
}

7. Use via API

GET /api/currencies?fields=code,name,exchangeRates&filters[code]=EUR

Files Changed

New Files

  • src/Database/Migrations/2024_12_20_000000_create_exchange_rates_table.php
  • src/Models/ExchangeRate.php
  • src/Models/Traits/ExchangeRateRelations.php
  • src/Services/ExchangeRateService.php
  • src/Commands/UpdateExchangeRates.php

Modified Files

  • config/world.php - Added exchange rate configuration
  • src/Models/Currency.php - Added exchangeRates relationship docblock
  • src/Models/Traits/CurrencyRelations.php - Added exchangeRates() method
  • src/Actions/Currency/IndexAction.php - Added exchangeRates to availableRelations
  • src/Actions/Currency/Transformers/IndexTransformer.php - Added exchangeRates handling
  • src/WorldServiceProvider.php - Registered UpdateExchangeRates command

Testing

  • ✅ Migration creates table correctly
  • ✅ Models have proper relationships
  • ✅ Service handles multiple API providers
  • ✅ Command executes successfully
  • ✅ Transformer returns latest exchange rate
  • ✅ Backward compatible (existing functionality unchanged)

Benefits

  1. Historical Tracking: All exchange rate updates are stored, enabling historical analysis
  2. Flexible API Support: Multiple providers supported, easy to add more
  3. Latest Rate Access: Automatically returns the most recent rate when requested
  4. Scheduled Updates: Can be integrated with Laravel's task scheduler
  5. No Breaking Changes: Fully backward compatible
  6. Follows Package Patterns: Consistent with existing codebase structure

Related Issue

Addresses the feature request for exchange rate support. The implementation follows the maintainer's suggestion to use a separate table with relationships rather than adding a column directly to the currencies table.

Checklist

  • Code follows PSR-2 coding standards
  • All new files have proper namespacing
  • Models use WorldConnection trait for custom database support
  • Configuration is properly documented
  • Command is registered in service provider
  • Backward compatibility maintained
  • Error handling implemented
  • Logging added for debugging

Copy link
Author

@Haeyzed Haeyzed left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feat: add exchange rates support with separate table and API integration

Implements exchange rates feature as requested in #<issue_number>.
Following maintainer's suggestion, exchange rates are stored in a separate
database table (exchange_rates) with a relationship to currencies, allowing
historical tracking of rates while using the latest entry for computations.

Features:

  • Create exchange_rates table migration with currency relationship
  • Add ExchangeRate model with Currency relationship
  • Add exchangeRates relationship to Currency model
  • Support fetching exchange rates via exchangeRates field in Currency API
  • Add ExchangeRateService with support for multiple API providers:
    • exchangerate-api.com (free tier, no API key required)
    • Fixer.io (requires API key)
    • CurrencyLayer (requires API key)
    • Custom API endpoint (configurable)
  • Add world:update-exchange-rates artisan command
  • Add configuration options in world.php config file
  • Automatically return latest exchange rate when requested

The implementation allows users to:

  1. Configure their preferred exchange rate API provider
  2. Fetch and store exchange rates via artisan command
  3. Schedule automatic updates using Laravel's task scheduler
  4. Access latest exchange rates through existing Currency API endpoints
  5. Maintain historical exchange rate data for analytics

Breaking changes: None

@nnjeim
Copy link
Owner

nnjeim commented Jan 13, 2026

@Haeyzed
thank you for all this, i was away for the holidays
i will be pulling back and testing this locally.
will revert back to you asap

@Haeyzed
Copy link
Author

Haeyzed commented Jan 13, 2026

@nnjeim ok, thanks ill be looking forward to that.

@Haeyzed
Copy link
Author

Haeyzed commented Jan 13, 2026

Kindly notify after testing.

@Haeyzed
Copy link
Author

Haeyzed commented Jan 20, 2026

@nnjeim Pls help look at this feature i really need it

@nnjeim
Copy link
Owner

nnjeim commented Jan 22, 2026

@nnjeim Pls help look at this feature i really need it

@Haeyzed
Hi and sorry for the delay. Kindly fork the repository and merge your code.
As such you can start using it and helping in testing.
Hopefully i will be able myself to feedback as well asap.

@nnjeim
Copy link
Owner

nnjeim commented Jan 22, 2026

@Haeyzed
I scanned thru the code and one additional feature would be to have the ability to tag the used currencies.
As such querying the provider api will be limited to those currencies.
If i am not mistaken this will limit the requests made.

@Haeyzed
Copy link
Author

Haeyzed commented Jan 22, 2026

@nnjeim Pls help look at this feature i really need it

@Haeyzed Hi and sorry for the delay. Kindly fork the repository and merge your code. As such you can start using it and helping in testing. Hopefully i will be able myself to feedback as well asap.

@nnjeim I dont have access to merge. You will be the one to help merge.

@nnjeim
Copy link
Owner

nnjeim commented Jan 22, 2026

@nnjeim Pls help look at this feature i really need it

@Haeyzed Hi and sorry for the delay. Kindly fork the repository and merge your code. As such you can start using it and helping in testing. Hopefully i will be able myself to feedback as well asap.

@nnjeim I dont have access to merge. You will be the one to help merge.

@Haeyzed
first fork nnjeim/world into Haeyzed/world
then merge your code

following your test results. i would look into limiting the currency exchange rates updates to selected currencies and not all.
do you have a solution for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants