laravel-lang/json-fallback
Laravel Lang JSON Fallback adds fallback loading for Laravel JSON translation files, ensuring missing keys or locales gracefully fall back to another language. Simple Composer install, integrates with Laravel’s localization system for smoother multilingual apps.
Installation:
composer require laravel-lang/json-fallback
Add the service provider to config/app.php:
'providers' => [
LaravelLang\JsonFallback\JsonFallbackServiceProvider::class,
],
Configuration: Publish the config file (optional):
php artisan vendor:publish --provider="LaravelLang\JsonFallback\JsonFallbackServiceProvider" --tag="config"
Update config/json-fallback.php to define fallback locales (e.g., fr → en):
'fallbacks' => [
'fr' => 'en',
'es' => 'en',
// Add more as needed
],
First Use Case:
Place JSON translation files in lang/json/ (e.g., lang/json/fr.json and lang/json/en.json). Use them in Blade, controllers, or APIs:
// Works like native Laravel trans(), but with JSON fallback
$translation = trans('json.key.missing_in_fr');
If fr.json lacks key.missing_in_fr, it falls back to en.json.
JSON Translation Files:
lang/json/{locale}.json (e.g., lang/json/fr.json):
{
"auth.login": "Connexion",
"auth.submit": "Se connecter"
}
trans() as usual:
trans('json.auth.login'); // Falls back to 'en.json' if 'fr.json' is missing the key
Dynamic Fallbacks:
app('translator')->setFallbackLocale('es'); // Temporarily override
trans('json.key'); // Falls back to 'es.json' instead of config
API Responses:
return response()->json([
'message' => trans('json.api.success'),
]);
Frontend Integration:
// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
input: {
'lang': path.resolve(__dirname, 'resources/lang/json/en.json'),
},
},
},
});
Translation Workflow:
lang/json/fr.json).jsonlint or custom scripts).Fallback Hierarchy:
config/json-fallback.php:
'fallbacks' => [
'fr' => 'en',
'es' => 'en',
'de' => 'en',
],
fr-CA → fr-FR → en), extend the package or use a custom provider.Testing:
$this->assertEquals('English fallback', trans('json.key.missing', [], 'fr'));
$this->app->make('translator')->setLoader(
new \Illuminate\Translation\FileLoader(app(), 'lang/json')
);
Cache Optimization:
php artisan cache:clear
php artisan view:clear
Nested JSON Handling:
{"auth": {"login": "value"}} → auth.login) before using this package, or pre-process files.Hybrid Translations:
lang/json/ and PHP arrays in lang/.Custom Providers:
JsonFallbackServiceProvider in config/app.php.Dynamic Locale Switching:
public function handle($request, Closure $next) {
app('translator')->setFallbackLocale($request->user()->preferred_fallback);
return $next($request);
}
JSON File Structure:
// ❌ Fails: Values are objects
{"key": {"nested": "value"}}
key.nested).Missing Fallback Locale:
en) is missing a key, the package returns the key itself (e.g., json.key.missing).
trans('json.key.missing', [], 'fr'); // Returns 'json.key.missing' if 'en.json' lacks the key
Service Provider Order:
JsonFallbackServiceProvider may override the fallback logic.JsonFallbackServiceProvider is loaded last in config/app.php.Caching Issues:
php artisan config:clear
php artisan cache:clear
Locale Auto-Detection:
trans() calls.Check Fallback Chain:
$translator = app('translator');
$locale = $translator->getLocale();
$fallback = $translator->getFallbackLocale();
logger("Fallback chain: {$locale} → {$fallback}");
Validate JSON Files:
php artisan json-fallback:validate (if the package adds this command) or a custom script to check for malformed JSON.Override Fallback Temporarily:
app('translator')->setLocale('fr');
app('translator')->setFallbackLocale('es');
trans('json.key'); // Test fallback to 'es'
Partial Translations:
Frontend Consistency:
Performance:
$translation = cache()->remember("trans.{$locale}.{$key}", now()->addHours(1), function() use ($locale, $key) {
return trans($key, [], $locale);
});
Extending Fallbacks:
JsonFallbackServiceProvider:
// Example: Add a custom fallback resolver
$this->app->singleton('translator', function ($app) {
$translator = new Translator($app['translation.loader'], $app['locale']);
$translator->setFallback($app['config']['json-fallback.custom_fallbacks']);
return $translator;
});
CI/CD Validation:
# Example: Check all JSON files for valid structure
find lang/json -name "*.json" -exec php -r 'if (!json_validate(file_get_contents($arg)) || !is_array(json_decode(file_get_contents($arg), true))) exit(1);' -- {} \;
Documentation:
Testing Edge Cases:
How can I help you explore Laravel packages today?