6

Is there any way that allows inserting translatable value in configuration file in application?

I have a custom configuration file at config/fox-reports.php and I'm trying to set a translatable configuration value looks like the following:

return [
    'attrs' => [
       'Product' => __('Product Title')
    ]
] 

When I run php artisan config:cache the following error is generated:

In Container.php line 729:

  Class translator does not exist
miken32
  • 42,008
  • 16
  • 111
  • 154
SaidbakR
  • 13,303
  • 20
  • 101
  • 195

2 Answers2

8

You can't use the __() helper in config files because it uses Translator class. Laravel loads config at the very beginning of the cycle when most of the services were not initialized yet.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • So there is no way other than translating the value at execution time. i.e from where it called from the application. Something like `__(config('fox-reports')['attrs']['Product']))` – SaidbakR Dec 31 '17 at 15:16
  • 1
    @SaidbakR keep all translations in language files and in config keep the key that you use in translation file. Then `__(config('fox-reports')['attrs']['Product'])` will work. – Alexey Mezenin Dec 31 '17 at 15:18
0

Just for completeness' sake to complement Alexey's answer, translations like this should be handled at a later time. Set up the configuration file with a default value that will be used if no translations exist.

config/fox-reports.php

return [
    'attrs' => [
       'Product' => 'Product Title'
    ]
];

Then set the translation key up in your localization JSON files, e.g.

resources/lang/fr/fr.json

{
    "Product Title": "Titre de produit"
}

And in your controller or wherever, you wrap the call to config() in the translation function:

// not like this:
// $title = config('foxreports.attrs.Product');
// but like this:
$title = __(config('foxreports.attrs.Product'));

If you need to have the default value detected by automated localization tools, just add it to a stub class somewhere, e.g.

<?php

namespace App\Stubs;

class Localization
{
    public method __construct()
    {
        __('Product Title');
    }
}
miken32
  • 42,008
  • 16
  • 111
  • 154