SaidbakR
SaidbakR

Reputation: 13544

Laravel class translator does not exist in a configuration file

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

Upvotes: 6

Views: 6737

Answers (2)

miken32
miken32

Reputation: 42696

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');
    }
}

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

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.

Upvotes: 8

Related Questions