Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Native Currency Names Laravel Package

laravel-lang/native-currency-names

Laravel Lang Native Currency Names provides localized, native-language currency names for Laravel apps. Easy to install via Composer and designed to complement Laravel localization workflows for displaying currencies correctly across locales.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel-lang/native-currency-names
    
  2. Publish translations (optional but recommended for customization):

    php artisan lang:publish --provider="LaravelLang\NativeCurrencyNames\NativeCurrencyNamesServiceProvider"
    

    This creates resources/lang/vendor/native-currency-names/ with all locale files.

  3. First Usage:

    // In Blade:
    {{ __('native-currency-names::currency.USD', [], 'en') }} // "US Dollar"
    {{ __('native-currency-names::currency.USD', [], 'ja') }} // "ドル"
    
    // In PHP:
    $currencyName = trans('native-currency-names::currency.USD', [], 'ja');
    

Where to Look First

  • Locale Files: Check resources/lang/vendor/native-currency-names/ for supported locales and currency codes.
  • Documentation: Official Docs for advanced usage (e.g., custom locales).
  • Service Provider: LaravelLang\NativeCurrencyNames\NativeCurrencyNamesServiceProvider for binding or extending functionality.

First Use Case

Localize currency names in a checkout flow:

<div class="currency-display">
    {{ __('native-currency-names::currency.' . $order->currency, [], $user->locale) }}
    {{ number_format($order->amount, 2) }}
</div>

Example Output:

  • For USD + ja locale → ドル 1000.00
  • For EUR + fr locale → Euros 1000,00

Implementation Patterns

Core Workflows

1. Basic Localization

Use Laravel’s translation helpers with the package’s namespace:

// Blade
{{ __('native-currency-names::currency.USD', [], 'en') }} // "US Dollar"
{{ __('native-currency-names::currency.JPY', [], 'ja') }} // "円"

// PHP
$name = trans('native-currency-names::currency.EUR', [], 'de'); // "Euro"

2. Dynamic Currency Display

Fetch currency names dynamically in controllers or models:

public function getOrderSummary(Order $order)
{
    $currencyName = trans(
        'native-currency-names::currency.' . $order->currency,
        [],
        $order->user->locale
    );
    return response()->json([
        'amount' => $currencyName . ' ' . number_format($order->amount, 2),
    ]);
}

3. Fallback Locales

Handle unsupported locale combinations gracefully:

// Falls back to 'en' if 'currency.USD' doesn't exist in 'zh'
{{ trans('native-currency-names::currency.USD', [], 'zh', 'en') }}

4. Integration with Eloquent

Add currency names to model attributes or accessors:

class Order extends Model
{
    public function getCurrencyNameAttribute()
    {
        return trans(
            'native-currency-names::currency.' . $this->currency,
            [],
            $this->user->locale
        );
    }
}

Usage:

$order->currency_name; // "Euro" (for EUR + de locale)

5. Blade Directives (Advanced)

Create a reusable directive for templates:

// app/Providers/AppServiceProvider.php
Blade::directive('currency', function ($currencyCode) {
    return "<?php echo trans('native-currency-names::currency.{$currencyCode}', [], app()->getLocale()); ?>";
});

Usage in Blade:

@currency($order->currency) {{ $order->amount }}

Integration Tips

  • Pair with laravel-money: Combine with myclabs/php-enum or laravel-money for full currency handling.
  • API Responses: Use the package in API resources:
    public function toArray($request)
    {
        return [
            'amount' => [
                'value' => $this->amount,
                'currency' => trans('native-currency-names::currency.' . $this->currency, [], $request->locale),
            ],
        ];
    }
    
  • Dynamic Locale Switching: Update currency names when users change locales:
    // Frontend (e.g., Vue/React)
    const updateCurrencyName = (currency, locale) => {
        return axios.get(`/api/currency-name?code=${currency}&locale=${locale}`);
    };
    

Gotchas and Tips

Pitfalls

  1. Currency Code Mismatch:

    • Issue: The package expects ISO 4217 currency codes (e.g., USD, EUR). Non-standard codes (e.g., US, EU) will return null.
    • Fix: Validate currency codes early in your workflow:
      use Illuminate\Support\Facades\Validator;
      Validator::extend('valid_currency', function ($attribute, $value, $parameters, $validator) {
          return trans('native-currency-names::currency.' . $value) !== null;
      });
      
  2. Missing Locale Files:

    • Issue: If a locale (e.g., ht for Haitian Creole) isn’t published, translations will fail silently.
    • Fix: Publish all locales upfront or handle fallbacks:
      $name = trans('native-currency-names::currency.USD', [], 'ht', 'en'); // Falls back to English
      
  3. Caching Quirks:

    • Issue: Laravel’s translation cache may not update immediately after publishing new locale files.
    • Fix: Clear the cache or use php artisan lang:publish --force:
      php artisan cache:clear
      php artisan view:clear
      
  4. Hybrid Currency Codes:

    • Issue: Crypto or custom currencies (e.g., BTC, DAI) may not be included.
    • Fix: Extend the package by adding custom locale files or override translations:
      // config/app.php
      'providers' => [
          LaravelLang\NativeCurrencyNames\NativeCurrencyNamesServiceProvider::class,
          App\Providers\CustomCurrencyProvider::class,
      ];
      

Debugging Tips

  • Check Available Locales:
    $locales = array_keys(config('lang.supported'));
    // Or inspect published files in `resources/lang/vendor/native-currency-names/`.
    
  • Log Missing Translations:
    $name = trans('native-currency-names::currency.XXX', [], 'xx');
    if (empty($name)) {
        Log::warning("Missing currency translation for {$currency} in {$locale}");
    }
    
  • Validate Data: Use the ISO 4217 list to verify currency codes.

Extension Points

  1. Add Custom Locales:

    • Publish the package, then add your locale file to resources/lang/vendor/native-currency-names/ (e.g., custom.json):
      {
          "USD": "Custom Dollar Name",
          "EUR": "Custom Euro Name"
      }
      
    • Register the locale in config/app.php:
      'supported' => ['en', 'ja', 'custom'],
      
  2. Override Translations:

    • Publish the package, then override specific translations in your app’s locale files:
      // resources/lang/en/native-currency-names.json
      {
          "USD": "Custom US Dollar Name"
      }
      
  3. Programmatic Access:

    • Bind the package’s service provider for direct access:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->bind('currencyNames', function () {
              return new \LaravelLang\NativeCurrencyNames\CurrencyNames();
          });
      }
      
    • Usage:
      $name = app('currencyNames')->get('USD', 'ja'); // "ドル"
      
  4. Testing:

    • Mock translations in tests:
      $this->app->setLocale('ja');
      $this->withoutTranslationBindings();
      trans()->addNamespace('native-currency-names', [
          'USD' => 'Test Dollar',
      ]);
      $this->assertEquals('Test Dollar', trans('native-currency-names::currency.USD'));
      

Performance Notes

  • Caching: The package leverages Laravel’s translation cache. For high-traffic apps, ensure config/cache.php is optimized.
  • Lazy Loading: Translations are loaded on-demand, so there’s no runtime overhead for unused currencies/locales.
  • Database: Avoid storing currency names in the DB—use the package’s translations directly for consistency.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony