Search code examples
phplaravel-5composer-phppackage-development

Provide localization from custom Laravel packages


I struggle on how to use localizations correctly with custom packages for laravel?
$this->loadTranslationsFrom(__DIR__ . '/../../resources/lang', 'package_lang'); does not provide me access to my nested translation-files in my views (Blade Templating).

My Folder-Structure

foo-package/
├── resources/
│   ├── lang/
│   │   ├── de/
│   │   │   └── subs/
│   │   │       ├── fields.php
│   │   │       └── general.php
│   │   └── en/
│   │       └── subs/
│   │           ├── fields.php
│   │           └── general.php
│   └── views/
│           └── subs/
│               ├── create.php
│               └── edit.php
└── src/
    └── Providers/
        └── PackageProvider.php

In my views I try to access it like this:

<label>{{ __('package_lang::subs/fields.name_of_subs') }}</label>

or

<button type="submit">{{ __('package_lang::subs/fields.create_sub') }}</button>

Resulting in returning the translation string key.

The ServiceProvider is loaded in my app.phpconfig, in which I have set the correct locale as well (Debug-Bar proves that). Tried composer dump-autoload, but no success.
I'm only getting this to work if I use the standard project folders of laravel project/resources/lang, which prevents me from using my prefered namespace package_lang:: and making my package ready for localization.

My Service Provider

namespace FooPackage\Providers;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

class PackageServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations');
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'package_views');
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'package_lang');
    }
}

Any idea how to solve it?

EDIT:

I have multiple packages following this folder structure.


Solution

  • Okay nevermind, the Post was missing out one major point.
    Multiple custom packages are involved, which uses the same namespace package_lang, which causes the problem.

    For whatever reason, the second namespace-parameter of $this->loadTranslationsFrom(__DIR__ . '/../../resources/lang', 'package_lang'); has to be uniquely defined!
    Changing this solves the problem.

    Just a side note: The above rule does however not apply to $this->loadViewsFrom(__DIR__.'/../../resources/views', 'package_views'); where multiple packages can have the same namespace.