Created
December 30, 2020 20:30
-
-
Save martio/d0f99daeda0e8d650d46ade0ccbc59c5 to your computer and use it in GitHub Desktop.
Detect language and set locale in Laravel using middleware
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 | |
| return [ | |
| /* | |
| |-------------------------------------------------------------------------- | |
| | Application Available Locales | |
| |-------------------------------------------------------------------------- | |
| | | |
| | The code must have the same name as in the languages folder. | |
| | | |
| */ | |
| 'available_locales' => ['cs', 'de', 'en', 'es', 'fr', 'pl', 'ru', 'sk'], | |
| ]; |
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\Http\Request; | |
| class SetLocale | |
| { | |
| /** | |
| * Handle an incoming request. | |
| * | |
| * @return mixed | |
| */ | |
| public function handle(Request $request, Closure $next) | |
| { | |
| if (!session()->has('locale')) { | |
| session()->put('locale', $request->getPreferredLanguage( | |
| config('app.available_locales') | |
| )); | |
| } | |
| app()->setLocale(session('locale')); | |
| return $next($request); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment