Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

I18N Laravel Package

cyberspectrum/i18n

Internationalization helpers for PHP: provides message translation utilities, locale handling, and i18n-related tooling to integrate multilingual text into your application or library. Useful for managing localized strings and adapting output by language and region.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cyberspectrum/i18n
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Cyberspectrum\I18n\I18nServiceProvider::class,
    ],
    
  2. Basic Configuration Publish the config file:

    php artisan vendor:publish --provider="Cyberspectrum\I18n\I18nServiceProvider" --tag="config"
    

    Edit config/i18n.php to define your locales and default locale:

    'locales' => [
        'en' => 'English',
        'es' => 'Spanish',
    ],
    'default' => 'en',
    
  3. First Use Case: Loading Translations Define a translation file in resources/lang/{locale}/messages.php:

    return [
        'welcome' => 'Welcome to our application',
        'greeting' => 'Hello, :name!',
    ];
    

    Use the facade in your code:

    use Cyberspectrum\I18n\Facades\I18n;
    
    $message = I18n::get('messages.welcome'); // "Welcome to our application"
    $greeting = I18n::get('messages.greeting', ['name' => 'John']); // "Hello, John!"
    

Implementation Patterns

Core Workflows

  1. Dynamic Locale Switching

    // Switch locale for a request
    I18n::setLocale('es');
    
    // Or use middleware to set locale based on request
    public function handle($request, Closure $next) {
        I18n::setLocale($request->header('Accept-Language') ?? config('i18n.default'));
        return $next($request);
    }
    
  2. Nested Translation Keys

    // File: resources/lang/en/validation.php
    return [
        'custom' => [
            'email' => [
                'required' => 'A valid email address is required.',
            ],
        ],
    ];
    
    // Usage
    $error = I18n::get('validation.custom.email.required');
    
  3. Fallback Locales Configure fallback locales in config/i18n.php:

    'fallbacks' => [
        'es' => ['en'],
        'fr' => ['en'],
    ],
    

    If a translation is missing in es, it will fall back to en.

  4. Translation Dictionaries Load and merge dictionaries dynamically:

    $dictionary = I18n::loadDictionary('custom', 'en', [
        'key1' => 'Value 1',
        'key2' => 'Value 2',
    ]);
    
    $value = I18n::get('custom.key1'); // "Value 1"
    
  5. Integration with Laravel Views

    // In a Blade view
    <h1>{{ __('messages.welcome') }}</h1>
    

    Or use the facade directly:

    <h1>{{ I18n::get('messages.welcome') }}</h1>
    
  6. Translation Copying Copy translations between locales:

    I18n::copyTranslations('en', 'es', 'messages');
    

Advanced Patterns

  1. Custom Translation Loaders Extend the package to load translations from external sources (e.g., databases, APIs):

    I18n::extend('database', function ($locale) {
        return DatabaseTranslationLoader::load($locale);
    });
    
  2. Translation Caching Cache translations for performance:

    I18n::cacheTranslations(true, 60); // Cache for 60 minutes
    
  3. Translation Validation Validate translations before deployment:

    $missing = I18n::validateTranslations('es', ['messages.welcome']);
    if (!empty($missing)) {
        // Handle missing translations
    }
    
  4. Translation Events Listen for translation events (e.g., translation.missing):

    I18n::listen('translation.missing', function ($locale, $key) {
        Log::warning("Missing translation for {$locale}.{$key}");
    });
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts Ensure translation keys do not conflict with Laravel’s built-in keys (e.g., auth, validation). Prefix custom keys if needed:

    I18n::get('app.custom.key');
    
  2. Locale Fallback Overrides Fallback locales may not work as expected if the fallbacks config is not properly set. Test with:

    I18n::setLocale('es');
    I18n::get('messages.welcome'); // Should fall back to 'en' if 'es' is missing
    
  3. Caching Issues Clear the cache after updating translations:

    php artisan cache:clear
    php artisan view:clear
    
  4. Dictionary Overwriting Be cautious when merging dictionaries—existing keys will be overwritten:

    I18n::loadDictionary('custom', 'en', ['key' => 'new_value']);
    // Overwrites any existing 'key' in the 'custom' dictionary.
    
  5. Missing Translation Handling The package does not throw exceptions for missing translations by default. Use the missing method to handle them:

    $translation = I18n::get('messages.missing', [], function ($locale, $key) {
        return "Fallback for {$key}";
    });
    

Debugging Tips

  1. Enable Debug Mode Set 'debug' => true in config/i18n.php to log missing translations.

  2. Check Loaded Dictionaries Inspect loaded dictionaries:

    $dictionaries = I18n::getLoadedDictionaries();
    
  3. Validate Translation Files Use Artisan to validate translation files:

    php artisan i18n:validate --locale=es --keys=messages.welcome,validation.required
    
  4. Override Default Behavior Extend the I18nManager class to customize behavior:

    class CustomI18nManager extends \Cyberspectrum\I18n\I18nManager {
        public function get($key, $replace = [], $default = null) {
            // Custom logic here
            return parent::get($key, $replace, $default);
        }
    }
    

    Bind the custom manager in a service provider:

    $this->app->bind(\Cyberspectrum\I18n\I18nManager::class, function ($app) {
        return new CustomI18nManager();
    });
    

Extension Points

  1. Custom Translation Directories Add additional directories to load translations from:

    I18n::addTranslationDirectory(resource_path('lang/custom'));
    
  2. Custom Translation File Format Extend the package to support JSON or YAML translations:

    I18n::extendLoader('json', function ($locale, $directory) {
        return JsonTranslationLoader::load($locale, $directory);
    });
    
  3. Translation Pluralization Add support for pluralization rules:

    I18n::setPluralizationRules('es', [
        'one' => '{{count}} mensaje',
        'other' => '{{count}} mensajes',
    ]);
    
  4. Translation Interpolation Customize how placeholders are replaced:

    I18n::setInterpolator(function ($translation, $replace) {
        return str_replace(array_keys($replace), array_values($replace), $translation);
    });
    
  5. Translation Middleware Create middleware to set the locale based on user preferences or session:

    public function handle($request, Closure $next) {
        I18n::setLocale($request->user()->locale ?? config('i18n.default'));
        return $next($request);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor