Created
April 27, 2020 11:51
-
-
Save zoltiecodes/3c6df61198110622861c04dd5b761906 to your computer and use it in GitHub Desktop.
Set Laravel language automatically and save to cookies
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\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