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.
Installation
composer require cyberspectrum/i18n
Add the service provider to config/app.php:
'providers' => [
// ...
Cyberspectrum\I18n\I18nServiceProvider::class,
],
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',
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!"
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);
}
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');
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.
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"
Integration with Laravel Views
// In a Blade view
<h1>{{ __('messages.welcome') }}</h1>
Or use the facade directly:
<h1>{{ I18n::get('messages.welcome') }}</h1>
Translation Copying Copy translations between locales:
I18n::copyTranslations('en', 'es', 'messages');
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);
});
Translation Caching Cache translations for performance:
I18n::cacheTranslations(true, 60); // Cache for 60 minutes
Translation Validation Validate translations before deployment:
$missing = I18n::validateTranslations('es', ['messages.welcome']);
if (!empty($missing)) {
// Handle missing translations
}
Translation Events
Listen for translation events (e.g., translation.missing):
I18n::listen('translation.missing', function ($locale, $key) {
Log::warning("Missing translation for {$locale}.{$key}");
});
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');
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
Caching Issues Clear the cache after updating translations:
php artisan cache:clear
php artisan view:clear
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.
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}";
});
Enable Debug Mode
Set 'debug' => true in config/i18n.php to log missing translations.
Check Loaded Dictionaries Inspect loaded dictionaries:
$dictionaries = I18n::getLoadedDictionaries();
Validate Translation Files Use Artisan to validate translation files:
php artisan i18n:validate --locale=es --keys=messages.welcome,validation.required
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();
});
Custom Translation Directories Add additional directories to load translations from:
I18n::addTranslationDirectory(resource_path('lang/custom'));
Custom Translation File Format Extend the package to support JSON or YAML translations:
I18n::extendLoader('json', function ($locale, $directory) {
return JsonTranslationLoader::load($locale, $directory);
});
Translation Pluralization Add support for pluralization rules:
I18n::setPluralizationRules('es', [
'one' => '{{count}} mensaje',
'other' => '{{count}} mensajes',
]);
Translation Interpolation Customize how placeholders are replaced:
I18n::setInterpolator(function ($translation, $replace) {
return str_replace(array_keys($replace), array_values($replace), $translation);
});
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);
}
How can I help you explore Laravel packages today?