I use this middleware to set my user's preferred currency. It works fine on my local machine but I just found out it creates issues with the session on my production server (login issues and validation errors not showing).
Any idea why?
app/Http/Middleware/PreferredCurrency.php
<?php
namespace App\Http\Middleware;
use App\Currency;
use Cache;
use Closure;
class PreferredCurrency
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Put the supported list of currencies in the cache and update exchange rates
Cache::remember('currencies', 60 * 60 * 24, function () {
Currency::updateExchangeRates();
return Currency::where('is_active', '1')->get();
});
// Look for the user preferred currency in the session
if (!$request->session()->has('preferred_currency')) {
// Grab the user currency based on IP location and try to match with the app supported currencies
$geoCurrencyCode = geoip()->getLocation()->currency;
$currency = Cache::get('currencies')->where('is_active', '1')->where('code', $geoCurrencyCode)->first();
// Fallback to default currency if we don't support the user's currency
if (empty($currency)) {
$currency = Cache::get('currencies')->where('code', 'USD')->first();
}
// Store the preferred currency in the session
session(['preferred_currency' => $currency]);
}
return $next($request);
}
}
app/Http/Kernel.php
//...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'PreferredCurrency' => \App\Http\Middleware\PreferredCurrency::class,
];
//...