Skip to content

Instantly share code, notes, and snippets.

@zoltiecodes
Created April 27, 2020 11:51
Show Gist options
  • Save zoltiecodes/3c6df61198110622861c04dd5b761906 to your computer and use it in GitHub Desktop.
Save zoltiecodes/3c6df61198110622861c04dd5b761906 to your computer and use it in GitHub Desktop.
Set Laravel language automatically and save to cookies
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
class SetLanguageMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Store the locale in cookie if it's in the request
if($request->has('locale')) {
Cookie::queue('locale', $request->get('locale'), 60 * 24 * 365);
}
// Determine the locale
$locale = $request->get('locale') ?? $request->cookie('locale') ?? substr($request->getPreferredLanguage(), 0, 2);
Lang::setLocale($locale);
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment