Skip to content

Instantly share code, notes, and snippets.

@martio
Created December 30, 2020 20:30
Show Gist options
  • Select an option

  • Save martio/d0f99daeda0e8d650d46ade0ccbc59c5 to your computer and use it in GitHub Desktop.

Select an option

Save martio/d0f99daeda0e8d650d46ade0ccbc59c5 to your computer and use it in GitHub Desktop.
Detect language and set locale in Laravel using middleware
<?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'],
];
<?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