Detect and change language on the fly with Laravel
If you’re builiding a multilingual site you may want to guess the user’s language in order to provide the correct content and still let her decide afterwards which language to use. So this a is two part problem:
Find a way to detect the user’s native language and tell Laravel to use it Provide a way for the user to change it and store that choice in session This tutorial will not cover how to make a multilingual Laravel application, for that I’ll suggest you take a look at Laravel Translatable and this tutorial on Laravel News.
Detect the user’s native language
There are multiple ways to detect language from a HTTP Request but as I only needed to check for english or french speakers, I choosed to check if those were present in the HTTP_ACCEPT_LANGUAGE HTTP directive and fallback to english if nothing matches.
The best way to do that is to use a Middleware. Type the following command from the console to create a new one: php artisan make:middleware SetLocale.
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
use App;
use Config;
class SetLocale
{
/**
*
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Session::has('locale')) {
$locale = Session::get('locale', Config::get('app.locale'));
} else {
$locale = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
if ($locale != 'fr' && $locale != 'en') {
$locale = 'en';
}
}
App::setLocale($locale);
return $next($request);
}
Link:
This post is submitted by our members. Submit a new post.
Tags: Tutorials Laravel 5 Laravel 5.1