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

Currency Bundle Laravel Package

cocolabs-sas/currency-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cocolabs-sas/currency-bundle
    

    Ensure the bundle is registered in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    Lexik\Bundle\CurrencyBundle\LexikCurrencyBundle::class => ['all' => true],
    
  2. Basic Configuration (config/packages/lexik_currency.yaml):

    lexik_currency:
        currencies:
            default: USD
            managed:
                - EUR
                - GBP
                - JPY
    
  3. First Use Case: Use the Twig filter in a template to format a value:

    {{ 1234.56 | currency_format('EUR') }}  {# Outputs: €1,234.56 #}
    

    Or convert and format:

    {{ 1234.56 | currency_convert_format('EUR', 'GBP') }}  {# Converts USD to GBP #}
    

Implementation Patterns

Core Workflows

  1. Currency Conversion in Controllers: Inject the currency_converter service to programmatically convert currencies:

    use Lexik\Bundle\CurrencyBundle\Services\CurrencyConverter;
    
    public function __construct(CurrencyConverter $converter) {
        $this->converter = $converter;
    }
    
    public function convertCurrency(Request $request) {
        $amount = $request->request->get('amount');
        $converted = $this->converter->convert($amount, 'USD', 'EUR');
        return new Response($converted);
    }
    
  2. Dynamic Currency Selection: Use a user’s locale or session to dynamically set the currency:

    {% set userCurrency = app.user.preferred_currency ?: 'USD' %}
    {{ order.total | currency_format(userCurrency) }}
    
  3. Database Storage: Store amounts in a base currency (e.g., USD) in the database and convert on display:

    // Store in DB (always in USD)
    $product->price = 99.99;
    
    // Display in user's currency
    {{ product.price | currency_convert_format('USD', app.user.currency) }}
    
  4. API Responses: Return formatted currencies in JSON responses:

    return $this->json([
        'price' => $product->price,
        'formatted_price' => $product->price | currency_convert_format('USD', 'EUR')
    ]);
    

Integration Tips

  1. Localization: Ensure your app’s locales are configured in config/packages/lexik_currency.yaml:

    lexik_currency:
        locales:
            EUR: 'fr_FR'
            GBP: 'en_GB'
    
  2. Symfony Forms: Use the CurrencyType for form fields:

    $builder->add('price', CurrencyType::class, [
        'currency' => 'EUR',
        'scale' => 2,
    ]);
    
  3. Caching Conversions: Cache conversion rates to avoid repeated API calls (e.g., using Symfony’s cache system):

    lexik_currency:
        cache: cache.app
    
  4. Custom Number Formatters: Extend the bundle’s formatter for bespoke rules:

    // src/Service/CustomCurrencyFormatter.php
    use Lexik\Bundle\CurrencyBundle\Formatter\CurrencyFormatter;
    
    class CustomCurrencyFormatter extends CurrencyFormatter {
        public function format($amount, $currency, $locale = null) {
            // Custom logic (e.g., rounding, symbols)
            return parent::format($amount, $currency, $locale);
        }
    }
    

    Register as a service:

    services:
        lexik_currency.formatter:
            class: App\Service\CustomCurrencyFormatter
            tags: ['lexik_currency.formatter']
    

Gotchas and Tips

Pitfalls

  1. Deprecated Filters:

    • Avoid currency_format for conversions (use currency_convert_format instead).
    • Example of wrong usage:
      {{ 100 | currency_format('USD', 'EUR') }}  {# Fails: Wrong signature #}
      
  2. Locale Mismatches:

    • Ensure the locale config matches the currency’s region (e.g., en_US for USD, fr_FR for EUR).
    • Symptoms: Incorrect decimal separators or symbols (e.g., $1,000 vs. 1.000,00).
  3. Unmanaged Currencies:

    • Only currencies listed in managed can be converted. Attempting to convert an unmanaged currency (e.g., currency_convert_format('USD', 'XYZ')) throws an exception.
  4. Floating-Point Precision:

    • Currency conversions may introduce rounding errors. Use round() or number_format() in Twig:
      {{ (100 | currency_convert_format('USD', 'EUR') | round(2)) | currency_format('EUR') }}
      

Debugging

  1. Check Conversion Rates: Dump the converter’s rates to verify data:

    $rates = $this->converter->getRates();
    dump($rates);  {# Should show exchange rates like ['EUR' => 0.85, 'GBP' => 0.75] #}
    
  2. Twig Debugging: Enable Twig strict mode to catch filter errors:

    twig:
        strict_variables: true
    
  3. Service Overrides: If extending the bundle, clear the cache after updates:

    php bin/console cache:clear
    

Extension Points

  1. Custom Exchange Rate Provider: Replace the default rate provider (e.g., for internal APIs):

    lexik_currency:
        provider: app.custom_rate_provider
    

    Implement Lexik\Bundle\CurrencyBundle\Provider\RateProviderInterface.

  2. Event Listeners: Listen for currency conversion events to log or audit changes:

    use Lexik\Bundle\CurrencyBundle\Event\CurrencyConvertEvent;
    
    public function onCurrencyConvert(CurrencyConvertEvent $event) {
        // Log conversion details
    }
    

    Register as a service with the kernel.event_listener tag.

  3. Symfony Messenger: Use the bundle’s CurrencyConvertMessage to decouple conversions from controllers:

    $message = new CurrencyConvertMessage($amount, 'USD', 'EUR');
    $this->messageBus->dispatch($message);
    
  4. Testing: Mock the CurrencyConverter in tests:

    $converter = $this->createMock(CurrencyConverter::class);
    $converter->method('convert')->willReturn(100.00);
    $this->container->set('lexik_currency.converter', $converter);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui