Last active
July 17, 2020 15:38
-
-
Save blood72/a1544b1963e8e8ff150900457fc47904 to your computer and use it in GitHub Desktop.
Laravel middleware that changes to user preferred language (without route prefix).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Support\Facades\File; | |
use Illuminate\Support\Str; | |
class PreferredLanguage | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
if ($request->has('lang') and $this->isSupportedLocale($request->input('lang'))) { | |
app()->setLocale($request->input('lang')); | |
} else if ($request->session()->has('locale') and $this->isSupportedLocale($request->session()->get('locale'))) { | |
app()->setLocale($request->session()->get('locale')); | |
} else if ($request->cookies->has('locale') and $this->isSupportedLocale($request->cookie('locale'))) { | |
app()->setLocale($request->cookie('locale')); | |
} else if ($request->getLanguages()) { | |
app()->setLocale($request->getPreferredLanguage($this->getSupportedLanguages())); | |
} | |
return $next($request); | |
} | |
/** | |
* @param string|null $locale | |
* @return bool | |
*/ | |
protected function isSupportedLocale($locale): bool | |
{ | |
return in_array($locale, (array) $this->getSupportedLanguages()); | |
} | |
/** | |
* @return array|null | |
*/ | |
protected function getSupportedLanguages() | |
{ | |
return config('language.support', $this->guessAvailableLanguages()); | |
} | |
/** | |
* @return array|null | |
*/ | |
protected function guessAvailableLanguages() | |
{ | |
try { | |
$lang = array_map(function ($path) { | |
return str_replace('-', '_', Str::afterLast($path, DIRECTORY_SEPARATOR)); | |
}, File::directories(resource_path('lang'))); | |
} catch (\Symfony\Component\Finder\Exception\DirectoryNotFoundException $exception) { | |
} finally { | |
return $lang ?? null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in
app/Http/Kernel.php