You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel添加货币选择器:实现价格转换的技术咨询

Answers to Your Currency Conversion Setup Questions

Hey there! Let's walk through your questions and next steps clearly—you've already laid a solid foundation, so let's build on that.

1. Is your current currency handling approach correct?

Yes, your base setup makes perfect sense:

  • Creating a Currency middleware to manage the active currency per request is the right pattern (it keeps currency logic centralized and applies it consistently across your app).
  • A dedicated config/currencies.php for supported currencies keeps your configuration organized and easy to update.
  • Setting a default currency in config/app.php ensures a reliable fallback if no user preference is set.

A quick validation check for your middleware: ensure it covers these key actions:

  • Checks for a user-selected currency (from a request parameter or session)
  • Validates the selected currency is in your config/currencies.php allowed list
  • Stores the valid currency in the user’s session (or binds it to the app container for easy access)
  • Falls back to the default IDR if no valid selection exists

2. Next steps to complete the implementation

Here’s a clear checklist of what to tackle next:

a. Register your Currency middleware

Open app/Http/Kernel.php and add your middleware to the appropriate group (global if you want it applied to all routes, or a custom group for routes that display prices):

// In the $middlewareGroups array (e.g., web group)
protected $middlewareGroups = [
    'web' => [
        // ... other existing middleware
        \App\Http\Middleware\Currency::class,
    ],
];

b. Build the frontend dropdown selector

Add a dropdown in your navigation bar that pulls supported currencies from your config. When the user selects a currency, submit it to a route that updates their session:

Example blade template code:

<form action="{{ route('currency.switch') }}" method="POST">
    @csrf
    <select name="currency" onchange="this.form.submit()">
        @foreach(config('currencies.available') as $code => $name)
            <option value="{{ $code }}" {{ session('currency', config('app.currency')) === $code ? 'selected' : '' }}>
                {{ $name }} ({{ $code }})
            </option>
        @endforeach
    </select>
</form>

Create a route and controller method to handle the switch:

// routes/web.php
Route::post('/currency/switch', [CurrencyController::class, 'switch'])->name('currency.switch');

// app/Http/Controllers/CurrencyController.php
public function switch(Request $request)
{
    $validated = $request->validate([
        'currency' => 'required|in:'.implode(',', array_keys(config('currencies.available'))),
    ]);

    session(['currency' => $validated['currency']]);

    return back();
}

c. Integrate your config with laravel-swap

First, publish the laravel-swap config file if you haven’t already:

php artisan vendor:publish --provider="Swap\Laravel\SwapServiceProvider"

Update config/swap.php to use your Fixer API key and tie into your currency config:

return [
    'default' => 'fixer',
    'services' => [
        'fixer' => [
            'access_key' => env('FIXER_API_KEY'),
            'enterprise' => false,
            'secure' => true,
        ],
        // ... other services if needed
    ],
    // Restrict SWAP to your supported currencies
    'options' => [
        'currencies' => array_keys(config('currencies.available')),
    ],
];

d. Create a helper function for easy price conversion

Add a helper function (e.g., in app/helpers.php) to convert prices anywhere in your app:

if (!function_exists('convert_price')) {
    function convert_price($amount, $fromCurrency = null, $toCurrency = null)
    {
        $from = $fromCurrency ?? config('app.currency');
        $to = $toCurrency ?? session('currency', config('app.currency'));

        if ($from === $to) {
            return $amount;
        }

        return Swap::latest()->convert($amount, $from, $to)->getValue();
    }
}

Autoload the helper file in composer.json:

"autoload": {
    "files": [
        "app/helpers.php"
    ],
    // ... rest of autoload config
}

Run composer dump-autoload to apply the change.

e. Update views to use the helper

Replace hardcoded price displays with the helper:

<!-- Old: {{ $product->price }} IDR -->
<!-- New: {{ convert_price($product->price) }} {{ session('currency', config('app.currency')) }} -->

f. Enable caching for exchange rates

laravel-swap has built-in caching—enable it in config/swap.php to avoid hitting Fixer’s API limits:

'cache' => [
    'enabled' => true,
    'store' => 'default',
    'ttl' => 3600, // Cache rates for 1 hour
],

3. How to tie your existing config to the SWAP package

To recap the key connections:

  • Use config/currencies.php to define all supported currencies (e.g., 'available' => ['IDR' => 'Indonesian Rupiah', 'USD' => 'US Dollar']).
  • Reference this list in config/swap.php to restrict SWAP to only your approved currencies (prevents invalid conversion requests).
  • In your helper function and middleware, pull the default currency from config('app.currency') and the user’s selected currency from the session—then pass these values to SWAP’s convert() method.

That’s it! You’ll have a fully functional currency switcher that updates all prices across your app once you complete these steps.

内容的提问来源于stack exchange,提问作者mafortis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:57:40