Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect language preference in Laravel 5

I want to detect my client language by getting the browser recommended language.

For Example, if you open the browser in Japan it will give me country code or country name current user opened like "en-jp" or "japan".

I try this code but it seems to display the language that I previously selected and by default it's English.

I set a Middleware and I need to exclude the api part because I have some routers pinging this address and router browser does not have language information which brick the system.

class BeforeMiddleware
{

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure $next
 * @return mixed
 */

protected $except_urls = [
    'api/*'
];

public function handle($request, Closure $next)
{
    $langArr = array("en", "fr");
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    } else {
        $languages[0] = "en";
    }
    if (Session::has('locale')) {
        App::setLocale(Session::get('locale'));
    } else {
        if (in_array($languages[0], $langArr))
            App::setLocale($languages[0]);
    }
    return $next($request);
}


} /* end class */

Thank you for you help.

like image 234
Nans Noel Avatar asked May 02 '16 15:05

Nans Noel


People also ask

What is @lang in laravel?

Laravel-lang is a collection of over 68 language translations for Laravel by developer Fred Delrieu (caouecs), including authentication, pagination, passwords, and validation rules. This package also includes JSON files for many languages.

How can I get laravel language?

I use App::getLocale() which is probably the most supported way as the App::setLocale('EN') method is used in the documentation. You can use this method everywhere. If it throughs an error somewhere, you can use \App::... to make it work.

Where is the language folder in laravel?

Language Files Language strings are stored in files within the app/lang directory. Within this directory there should be a subdirectory for each language supported by the application.

How do I get laravel locale?

To fetch current locale you should use App::getLocale() or App::isLocale('...') . Localization. You can also use app()->getLocale() which in Blade would be {{ app()->getLocale() }} .


2 Answers

Or you can use Illuminate\Http\Request::getPreferredLanguage

Like this, in middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;

class Locale {

  const SESSION_KEY = 'locale';
  const LOCALES = ['en', 'cs'];

  public function handle(Request $request, Closure $next) {
    /** @var Session $session */
    $session = $request->getSession();

    if (!$session->has(self::SESSION_KEY)) {
      $session->put(self::SESSION_KEY, $request->getPreferredLanguage(self::LOCALES));
    }

    if ($request->has('lang')) {
      $lang = $request->get('lang');
      if (in_array($lang, self::LOCALES)) {
        $session->put(self::SESSION_KEY, $lang);
      }
    }

    app()->setLocale($session->get(self::SESSION_KEY));

    return $next($request);
  }
}
like image 65
Daniel Šádek Avatar answered Sep 16 '22 20:09

Daniel Šádek


To simply get the locale from the header, you can grab the http-accept-language value from the request. This is accessible via a facade or you can use the request variable in your middleware:

Request::server('HTTP_ACCEPT_LANGUAGE')

// OR

$request->server('HTTP_ACCEPT_LANGUAGE');

This returns a string which looks like this: en-GB,en;q=0.8. You can then parse it (perhaps using explode()?) and grab the language from there.

However, this sort of thing can sometimes get complicated. If you need to do something more advanced, there's a package which can do all of this for you:

https://github.com/mcamara/laravel-localization

like image 31
edcs Avatar answered Sep 19 '22 20:09

edcs