Laravel-阅读所有可用语言,但所有翻译均为德语

时间:2019-07-19 10:18:53

标签: laravel laravel-5 locale service-provider

我在laravel中有一个服务提供商,该服务提供商从locale读取所有可用的语言,并将它们保存在缓存文件中。一切正常,但所有翻译均为德语。我希望以deen语言获得它们。 这是ServiceProvider中的代码:

$minutes = 24 * 60;
Cache::remember('translations', $minutes, function () {
    $directories = array('de', 'en');
    $collection = new \stdClass;
    foreach ($directories as $directory) {
        $path = resource_path('lang/' . $directory);
        $allTranslations = collect(File::allFiles($path))->flatMap(function ($file, $directory) {
            return [
                ($translation = $file->getBasename('.php')) => trans($translation, array(), null, $directory),
            ];
        });
        $allModuleTranslations = collect(File::allFiles($path . '/modul'))->flatMap(function ($file, $directory) {
            return [
                ($translation = $file->getBasename('.php')) => trans('modul/' . $translation, array(), null, $directory),
            ];
        });
        $collection->$directory = $allTranslations->merge($allModuleTranslations);
    }
    return json_encode($collection);
});

有人可以看到为什么它返回所有德语单词吗?

结果如下:

{
   de:
      auth:
         failed: "Diese Zugangsdaten wurden nicht in unserer Datenbank gefunden."
         throttle: "Zu viele Login Versuche. Versuchen Sie es bitte in :seconds Sekunden."
   en:
      auth:
         failed: "Diese Zugangsdaten wurden nicht in unserer Datenbank gefunden."
         throttle: "Zu viele Login Versuche. Versuchen Sie es bitte in :seconds Sekunden."
}

1 个答案:

答案 0 :(得分:1)

  1. 您必须使用$directory从父范围导入use变量,它不会与flatMap()回调一起传递

  2. trans仅具有3个参数,但您要传递4个参数

    mixed trans(string $key, array $replace = [], string|null $locale = null)

这应该有效:

$minutes = 24 * 60;
Cache::remember('translations', $minutes, function () {
    $directories = array('de', 'en');
    $collection = new \stdClass;
    foreach ($directories as $directory) {
        $path = resource_path('lang/' . $directory);
        $allTranslations = collect(File::allFiles($path))
            ->flatMap(function ($file) use ($directory) {
                return [
                    ($translation = $file->getBasename('.php')) => trans($translation, array(), $directory),
                ];
            });
        $allModuleTranslations = collect(File::allFiles($path . '/modul'))
            ->flatMap(function ($file) use ($directory) {
                return [
                    ($translation = $file->getBasename('.php')) => trans('modul/' . $translation, array(), $directory),
                ];
            });
        $collection->$directory = $allTranslations->merge($allModuleTranslations);
    }
    return json_encode($collection);
});