binsoul/common-i18n
Common i18n utilities for PHP applications. Provides lightweight helpers for working with translations and locales, aiming to reduce boilerplate around internationalization in shared code across projects.
Installation
composer require binsoul/common-i18n
Publish the config file (if available):
php artisan vendor:publish --provider="Binsoul\CommonI18n\CommonI18nServiceProvider"
Basic Configuration
Edit config/common-i18n.php to define:
default_locale)locales)fallback_locale)paths for JSON/CSV files)First Use Case: Localizing Strings Load translations in a controller or service:
use Binsoul\CommonI18n\Facades\I18n;
$greeting = I18n::trans('greetings.hello'); // Assumes 'en' locale
Locale Switching Dynamically switch locales in middleware or routes:
I18n::setLocale('fr'); // Force French locale
resources/lang/{locale}/messages.json or .csv.
Example (en/messages.json):
{
"greetings": {
"hello": "Hello, {{ name }}!"
}
}
{{ name }}) for runtime values:
I18n::trans('greetings.hello', ['name' => 'John']);
Bind locales to routes (e.g., /fr/dashboard):
Route::prefix('{locale}')->middleware('locale')->group(function () {
// Routes here
});
Middleware (app/Http/Middleware/LocaleMiddleware.php):
public function handle($request, Closure $next) {
I18n::setLocale($request->locale);
return $next($request);
}
Configure fallback locales in config/common-i18n.php:
'fallback_locale' => 'en',
'fallback_chain' => ['en', 'fr'],
The package will automatically fall back if a translation is missing.
Extend Blade directives for inline translations:
// Add to AppServiceProvider::boot()
Blade::directive('trans', function ($expression) {
return "<?php echo \Binsoul\CommonI18n\Facades\I18n::trans($expression); ?>";
});
Usage in Blade:
<h1>@trans('greetings.hello', ['name' => 'Alice'])</h1>
Override Laravel’s validation messages:
$validator = Validator::make($data, $rules);
$validator->setMessages(I18n::getValidatorMessages());
Mock translations in tests:
I18n::setLocale('test');
I18n::translator()->set('test.key', 'Mocked value');
$this->assertEquals('Mocked value', I18n::trans('test.key'));
Missing Config Keys
Ensure config/common-i18n.php exists and is properly configured. The package may silently fail if paths or locales are misconfigured.
php artisan vendor:publish and verify the config.Locale Not Set
If I18n::getLocale() returns null, translations will fail. Always set a default locale in the config or middleware.
I18n::setLocale(config('app.locale', 'en'));
Caching Issues Translations may not update if the cache is enabled. Clear the cache after adding new translations:
php artisan cache:clear
php artisan view:clear
CSV Parsing Quirks The package may not handle malformed CSV files gracefully. Validate your CSV structure (e.g., UTF-8 encoding, no extra commas).
Namespace Conflicts
If you have a class or trait named I18n, the facade may conflict. Rename or alias the facade:
use Binsoul\CommonI18n\Facades\I18n as I18nTranslator;
dd(I18n::translator()->get('*')); // Dump all loaded translations
I18n::translator()->setDebug(true); // Logs missing translations
AppServiceProvider::boot():
I18n::translator()->setMissingCallback(function ($key) {
Log::warning("Missing translation key: {$key}");
});
Custom Translator Extend the translator for database-backed translations:
I18n::translator()->extend('db', function ($locale) {
return new DatabaseTranslator($locale);
});
I18n::translator()->setTranslator('db');
Pluralization Rules Override pluralization logic for languages like Arabic or Russian:
I18n::translator()->setPluralizer('ar', function ($count) {
return $count == 1 ? 'singular' : 'plural';
});
Add New File Formats Implement a custom loader for YAML or XML:
I18n::translator()->addLoader('yaml', function ($locale, $loader) {
return new YamlLoader($locale, $loader);
});
Locale Detection Integrate with user agents or cookies for automatic locale detection:
$locale = request()->cookie('locale') ?? request()->header('Accept-Language');
I18n::setLocale($locale);
I18n::translator()->load('en', 'common', 'messages');
'fallback_locale' => null in production to fail fast on missing translations.// resources/lang/en/messages.json
{
"validation": {
"required": "The {{ field }} field is required."
}
}
How can I help you explore Laravel packages today?