Astrotomic / laravel-translatable

A Laravel package for multilingual models
https://docs.astrotomic.info/laravel-translatable/
MIT License
1.25k stars 158 forks source link

How to add new language dynamically #430

Open camohub opened 2 months ago

camohub commented 2 months ago

Hi there, can somebody tell me please how to achieve this. I need to add new language to the app dynamically. There is config/translatable.php which contains

    'locales' => ['en', 'cs', 'cz', 'sk', 'pl',  'de', 'hu',  'uk',  'us', 'gb', ],

This does not allow to add new language which is not defined in this array. I have a controller which want to add new languages and tries to do it this way.

        config([
            'translatable.locales'         => $newLocales,
            'translatable.locale'          => $data['default_language'],
            'translatable.fallback_locale' => $data['default_language'],
        ]);

I thought this will cange the config and library will add new language. But the library allow only the languages which are in config file array. How can I dynamically add new languages to the application? Thanks.

Oleksandr-Moik commented 2 months ago

Hi, @camohub. It does not work, because the library does not access directly to the configurations and works with the helper class Locales. In general, after setting new locales you need to reload it with method load

config([
    'translatable.locales'         => $newLocales,
    'translatable.locale'          => $data['default_language'],
    'translatable.fallback_locale' => $data['default_language'],
]);

resolve(Locales::class)->load();

You can check how it's works in test suite: https://github.com/Astrotomic/laravel-translatable/blob/0d065da7fb06b4b957afce79fdda159764561345/tests/LocalesTest.php#L21-L36

camohub commented 2 months ago

Thank you very much. It seems it works. Where in the documentation I can find this?

Oleksandr-Moik commented 2 months ago

@camohub, about load method - https://docs.astrotomic.info/laravel-translatable/package/locales-helper#load

camohub commented 2 months ago

Thanks again.