JanBoehmer
JanBoehmer

Reputation: 555

Localization in a custom Laravel Package

My service provider of my custom package has the following lines in the boot() method:

$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'name');
$this->publishes([
            __DIR__.'/../resources/lang' => resource_path('lang/vendor/name'),
        ], 'lang');

I ran the php artisan vendor:publish command and the packages/vendorname/packagename/resources/lang/de.json file was successfully copied to the project.

The translation is not working. I tried copying to the /lang/vendor/name/ folder as well.

When I move my de.json file manually to /lang then the translation is working. To there is no issue with the file itself.

I tried to clear all caches already.

Upvotes: 3

Views: 1505

Answers (1)

hossein emami
hossein emami

Reputation: 286

I am not sure why, But, it seems that Laravel just loads only the JSON translation files of the main project and the first package in the Vendor folder.

My solution is:

  1. for loading the JSON translation files from your package, you have to use loadJsonTranslationsFrom in your package's service provider:

    class CustomeServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap the package services.
         *
         * @return void
         */
        public function boot()
        {
            $this->loadJsonTranslationsFrom(__DIR__.'/../resources/lang');
        }
    }
    
  2. In your JSON file you can use your package name as a prefix for every key. for example, if your package name is MyPackage, your en.json file looks like:

    {
      "MyPackage::email": "Email",
      "MyPackage::username": "Username",
      ...
    }
    
  3. You can use some helper functions of Laravel to load your translation keys:

    trans('MyPackage::email'); // returns "Email"
    OR
    __('MyPackage::username'); // returns "Username"
    

You can follow the links below for more information:

https://laracasts.com/discuss/channels/laravel/loadjsontranslationsfrom-does-not-load-all-json-translation-files

https://github.com/laravel/framework/issues/17923

Laravel 5 loadJsonTranslationsFrom method does not load all JSON translation files from packages

https://github.com/nWidart/laravel-modules/pull/412

https://github.com/laravel/framework/pull/20599

Upvotes: 2

Related Questions