Skip to content

Instantly share code, notes, and snippets.

@blood72
Last active July 17, 2020 15:38
Show Gist options
  • Save blood72/a1544b1963e8e8ff150900457fc47904 to your computer and use it in GitHub Desktop.
Save blood72/a1544b1963e8e8ff150900457fc47904 to your computer and use it in GitHub Desktop.
Laravel middleware that changes to user preferred language (without route prefix).
<?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;
}
}
}
@blood72
Copy link
Author

blood72 commented Jul 14, 2020

in app/Http/Kernel.php

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            // ...

            \App\Http\Middleware\PreferredLanguage::class,
        ],

        // ...
    ];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment