spatie/laravel-translation-loader

repository·main·Indexed 21 days ago

https://github.com/spatie/laravel-translation-loader

A package for Laravel and Lumen applications to store and manage translation strings in a database instead of relying solely on static language files. It integrates with Laravel's native __ helper, supports mixing file-based and database-based translations, and allows for custom translation providers by implementing the TranslationLoader interface.

Tokens
2.5K
Snippets
10
Records
11
Agent score
74%

What's inside spatie/laravel-translation-loader

  1. How to create a custom translation provider

    main

    If you want to load translations from a source other than the database (e.g., YAML or CSV files), you can implement the Spatie\TranslationLoader\TranslationLoaders\TranslationLoader interface.

    Your implementation must include the loadTranslations method, which returns an array of translations for a specific locale and group. Once implemented, register your class in the translation_loaders array within the package configuration file.

    namespace Spatie\TranslationLoader\TranslationLoaders;
    
    interface TranslationLoader
    {
        /**
         * Returns all translations for the given locale and group.
         */
        public function loadTranslations(string $locale, string $group): array;
    }
  2. Install spatie/laravel-translation-loader

    main

    Install the package via Composer and replace the default Laravel translation service provider with the one provided by this package. You must also publish and run the migrations to create the language_lines table.

    composer require spatie/laravel-translation-loader

    In config/app.php (Laravel) or bootstrap/app.php (Lumen), replace:

    Illuminate\Translation\TranslationServiceProvider::class,

    with:

    Spatie\TranslationLoader\TranslationServiceProvider::class,

    Publish and run migrations

    php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="translation-loader-migrations" php artisan migrate

  3. Create and use database translations

    main

    To store translations in the database, create and save an instance of the Spatie\TranslationLoader\LanguageLine model. You can then retrieve these translations using Laravel's standard __ helper function.

    If a translation exists in both a language file and the database, the database version takes precedence. To override or store JSON translation lines, set the group to *.

    use Spatie\
    TranslationLoader\\LanguageLine;
    
    // Create a translation
    LanguageLine::create([
       'group' => 'validation',
       'key' => 'required',
       'text' => ['en' => 'This is a required field', 'nl' => 'Dit is een verplicht veld'],
    ]);
    
    // Retrieve a translation
    __('validation.required'); // returns 'This is a required field'
    
    app()->setLocale('nl');
    __('validation.required'); // returns 'Dit is een verplicht veld'
    
    // For JSON translations, use group => '*'
    LanguageLine::create([
       'group' => '*',
       'key' => 'some.json.key',
       'text' => ['en' => 'Hello'],
    ]);
  4. Configure the translation loader

    main

    You can publish the configuration file to customize which loaders are used, which model is used for database translations, and which manager handles the translations.

    Note: In Lumen, publishing assets via Artisan commands does not work out of the box; you must manually copy the files from the repository.

    php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="translation-loader-config"
  5. Configure the translation manager class

    main

    The package allows you to specify which class should be used as the translation.loader via the translation-loader.translation_manager configuration key. This class is instantiated as a singleton and is responsible for loading translation lines. By default, the package uses a manager that replaces the standard Laravel FileLoader.

    // In your config/translation-loader.php
    return [
        'translation_manager' => Spatie\TranslationLoader\TranslationLoaderManager::class,
    ];
  6. Configure the database model for the translation loader

    main

    The Db translation loader relies on a specific Eloquent model to fetch translations from the database. You must configure this model in your config/translation-loader.php file using the model key.

    The configured model class must implement or extend the Spatie\TranslationLoader\LanguageLine class to ensure it has the necessary getTranslationsForGroup method.

    // config/translation-loader.php
    
    return [
        'model' => App\Models\LanguageLine::class,
    ];
  7. Reference: Translation Loader Configuration Keys

    main

    The following keys are available in the published configuration file:

    • translation_loaders: An array of classes that implement Spatie\TranslationLoader\TranslationLoaders\TranslationLoader. These are the sources used to fetch translations.
    • model: The Eloquent model used by the Db translation loader. It must extend Spatie\TranslationLoader\LanguageLine.
    • translation_manager: The class responsible for overriding the default Laravel translation.loader.
    return [
        'translation_loaders' => [
            Spatie\TranslationLoader\TranslationLoaders\Db::class,
        ],
    
        'model' => Spatie\TranslationLoader\LanguageLine::class,
    
        'translation_manager' => Spatie\TranslationLoader\TranslationLoaderManager::class,
    ];
  8. Troubleshoot InvalidConfiguration exception

    main

    If you encounter an InvalidConfiguration exception, it typically means the model class you have configured for the translation loader is incorrect. Specifically, the class you provided must extend Spatie\TranslationLoader\LanguageLine.

    If you see the error message You have configured an invalid class {className}. A valid class extends Spatie\TranslationLoader\LanguageLine., ensure that your custom model implementation correctly inherits from the required base class.

  9. Manually flush translation group cache

    main

    If you need to manually clear the cached translations for a specific group, you can call flushGroupCache() on a LanguageLine instance. This will remove the cached entries for all locales present in that specific line's text attribute.

    Note: The model automatically handles cache flushing on saved and deleted events, so manual flushing is typically only necessary for custom cache management logic.

    $languageLine->flushGroupCache();
  10. Manage individual translation lines

    main

    The LanguageLine model represents a single translation entry in your database. You can interact with specific locales using the following methods:

    • getTranslation(string $locale): Retrieves the translation for the specified locale. If the locale is missing, it automatically falls back to the app.fallback_locale configured in your Laravel application.
    • setTranslation(string $locale, string $value): Sets or updates the translation for a specific locale. This method returns the model instance to allow for chaining.

    Note: The text attribute is stored as a JSON array in the database, mapping locales to their respective translation strings.

    $line = LanguageLine::where('key', 'welcome_message')->first();
    
    // Get translation with fallback support
    $text = $line->getTranslation('fr');
    
    // Set a new translation and save
    $line->setTranslation('fr', 'Bonjour le monde')->save();
  11. Retrieve translations for a specific group and locale

    main

    Use LanguageLine::getTranslationsForGroup(string $locale, string $group) to fetch all translations for a given group.

    • If $group is set to '*', the method returns a flat array where keys are the translation keys and values are the translated strings.
    • For any other group name, the method returns a nested array structure using Arr::set, allowing you to represent hierarchical translation keys (e.g., auth.login.success).

    Results are cached indefinitely using the cache key format spatie.translation-loader.{group}.{locale}. The cache is automatically invalidated whenever a LanguageLine model is saved or deleted.

    use Spatie\TranslationLoader\LanguageLine;
    
    // Get a nested array of translations for the 'messages' group in English
    $translations = LanguageLine::getTranslationsForGroup('en', 'messages');
    
    // Get a flat array of all translations across all groups for English
    $allTranslations = LanguageLine::getTranslationsForGroup('en', '*');