Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

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

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

{{ app()->getLocale() }}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'
];

enter image description here

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"
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...