How do I fetch name of locale (language) not just a locale string, but rather the name of that language in LARAVEL?

和自甴很熟 提交于 2019-12-13 08:27:27

问题


How do I fetch name of locale (language) not just a locale string, but rather the name of that language in LARAVEL?

{{ app()->getLocale() }}

回答1:


Laravel doesn't have this information. You need to add it manually by creating table or config with locales and their languages names.




回答2:


I resolved this by adding an entry to a translation file using Laravel Localization.

https://laravel.com/docs/5.7/localization

In AppServiceProvider@boot :

$language = Settings::get('language'); // Fetch saved language preference
$language = ($language === null) ? config('app.locale','ENG') : $language->value;

App::setLocale($language);

$languages = Cache::rememberForever('languages',
    function () {

        $walkable = File::directories(App()->basePath() . '/resources/lang');
        $output = [];

        array_walk($walkable,
            function($value) use (&$output) {

                $parts = explode('/', $value);
                $key = end( $parts );

                $require = $value . '/language.php';

                if (file_exists($require)) {
                    $output[$key] = require($require);
                }

            }
        );

    return $output;
});

config(['app.languages' => $languages]); 

I then have an entry for each language in dir resources/lang/LOCALE_ISO_3 (ENG/SPA/ITA...)/language.php

<?php // Spanish (SPA)

return [
    'default' => 'Spanish',
    'locale' => 'Español'
];

To then get a list of available languages:

dd( config('app.languages') );

Results in:

array:3 [▼
  "ENG" => array:2 [▼
    "default" => "English"
    "locale" => "English"
  ]
  "ITA" => array:2 [▼
    "default" => "Italian"
    "locale" => "Italiano"
  ]
  "SPA" => array:2 [▼
    "default" => "Spanish"
    "locale" => "Español"
  ]
]

To get current active language:

dd(trans('language'));

Gives you:

array:2 [▼
  "default" => "English"
  "locale" => "English"
]


来源:https://stackoverflow.com/questions/53428428/how-do-i-fetch-name-of-locale-language-not-just-a-locale-string-but-rather-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!