DengDeng
DengDeng

Reputation: 543

Does laravel not detect request locale automatically?

I am learning laravel 5.4 locale chapter. When I write code to test, I get a question. For example, I have two language directories in my resources/lang directory:

/resources
    /lang
        /en
            messages.php
        /zh-CN
            messages.php

I set default locale is zh-CN, fallback locale is en. When I set Accept-Language to zh-CN, I can get translation string in zh-CN. But when I set Accept-Language to en, I still get string in zh-CN. So laravel does not detect request locale automatically? And If my application want to show english to those Accept-Language is en, and show chinese to those Accept-Language is zh-CN, I need to do it manually, is that correct? I though laravel will detect request locale automatically.

Upvotes: 2

Views: 3283

Answers (2)

fan711
fan711

Reputation: 716

First configure the available languages in your config/app.php.

    'available_locales' => array('en', 'de', 'fr', 'it'),

Now add this code to your routes/web.php. It will detect the browser language and set the locale if the language is available.

    $availableLanguages = Config::get('app.available_locales');
    $lang = Request::getPreferredLanguage($availableLanguages);
    if ($lang) Config::set('app.locale', $lang);

Upvotes: 1

lewis4u
lewis4u

Reputation: 15057

After doing those changes it is always recommended to run these commands:

php artisan cache:clear
php artisan view:clear
php artisan route:clear

Upvotes: 0

Related Questions