2017-01-18 22:31:35 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
2019-02-27 23:44:50 +08:00
|
|
|
use Illuminate\Support\Arr;
|
2017-01-18 22:31:35 +08:00
|
|
|
use Illuminate\Http\Request;
|
|
|
|
use Illuminate\Http\Response;
|
|
|
|
|
|
|
|
class DetectLanguagePrefer
|
|
|
|
{
|
|
|
|
public function handle($request, \Closure $next)
|
|
|
|
{
|
|
|
|
$response = $next($request);
|
|
|
|
|
|
|
|
if ($response instanceof Response) {
|
|
|
|
$response->cookie('locale', config('app.locale'));
|
|
|
|
}
|
|
|
|
|
|
|
|
return $response;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function detect(Request $request)
|
|
|
|
{
|
|
|
|
$locale = $request->input('lang') ?: ($request->cookie('locale') ?: $request->getPreferredLanguage());
|
2018-02-16 17:31:04 +08:00
|
|
|
|
|
|
|
// If current locale is an alias of other locale
|
2019-02-27 23:44:50 +08:00
|
|
|
if (($info = Arr::get(config('locales'), $locale)) && ($alias = Arr::get($info, 'alias'))) {
|
2017-01-18 22:31:35 +08:00
|
|
|
$locale = $alias;
|
|
|
|
}
|
|
|
|
|
|
|
|
app()->setLocale($locale);
|
2019-04-06 23:22:36 +08:00
|
|
|
session(['locale' => config('app.locale')]);
|
2017-01-18 22:31:35 +08:00
|
|
|
}
|
|
|
|
}
|