Laravel class translator does not exist in a configuration file
Asked Answered
S

2

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
Spencer answered 31/12, 2017 at 15:10 Comment(0)
C
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.

Clintonclintonia answered 31/12, 2017 at 15:12 Comment(2)
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']))Spencer
@Spencer 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.Clintonclintonia
P
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');
    }
}
Planography answered 11/12, 2021 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.