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

Json Fallback Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel-lang/json-fallback
    

    Add the service provider to config/app.php:

    'providers' => [
        LaravelLang\JsonFallback\JsonFallbackServiceProvider::class,
    ],
    
  2. 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., fren):

    'fallbacks' => [
        'fr' => 'en',
        'es' => 'en',
        // Add more as needed
    ],
    
  3. 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.


Implementation Patterns

Usage Patterns

  1. JSON Translation Files:

    • Store translations in lang/json/{locale}.json (e.g., lang/json/fr.json):
      {
          "auth.login": "Connexion",
          "auth.submit": "Se connecter"
      }
      
    • Use trans() as usual:
      trans('json.auth.login'); // Falls back to 'en.json' if 'fr.json' is missing the key
      
  2. Dynamic Fallbacks:

    • Override fallbacks per request (e.g., for user-specific hierarchies):
      app('translator')->setFallbackLocale('es'); // Temporarily override
      trans('json.key'); // Falls back to 'es.json' instead of config
      
  3. API Responses:

    • Return JSON translations directly in API responses:
      return response()->json([
          'message' => trans('json.api.success'),
      ]);
      
  4. Frontend Integration:

    • Bundle JSON files for SPAs (Vue/React) via Laravel Mix/Vite:
      // vite.config.js
      export default defineConfig({
          build: {
              rollupOptions: {
                  input: {
                      'lang': path.resolve(__dirname, 'resources/lang/json/en.json'),
                  },
              },
          },
      });
      
    • Use the package to ensure missing keys in frontend JSON files fall back to backend defaults.

Workflows

  1. Translation Workflow:

    • Step 1: Add a new locale (e.g., lang/json/fr.json).
    • Step 2: Translate partial keys; missing keys auto-fall back.
    • Step 3: Validate JSON files in CI (e.g., using jsonlint or custom scripts).
  2. Fallback Hierarchy:

    • Define fallbacks in config/json-fallback.php:
      'fallbacks' => [
          'fr' => 'en',
          'es' => 'en',
          'de' => 'en',
      ],
      
    • For multi-level fallbacks (e.g., fr-CAfr-FRen), extend the package or use a custom provider.
  3. Testing:

    • Test fallbacks with missing keys:
      $this->assertEquals('English fallback', trans('json.key.missing', [], 'fr'));
      
    • Mock JSON files for isolated testing:
      $this->app->make('translator')->setLoader(
          new \Illuminate\Translation\FileLoader(app(), 'lang/json')
      );
      

Integration Tips

  1. Cache Optimization:

    • Clear translation cache after adding new locales:
      php artisan cache:clear
      php artisan view:clear
      
  2. Nested JSON Handling:

    • Flatten nested JSON keys (e.g., {"auth": {"login": "value"}}auth.login) before using this package, or pre-process files.
  3. Hybrid Translations:

    • Mix JSON and PHP array translations by ensuring JSON files are in lang/json/ and PHP arrays in lang/.
  4. Custom Providers:

    • If using a custom translation provider (e.g., database), ensure it’s registered after JsonFallbackServiceProvider in config/app.php.
  5. Dynamic Locale Switching:

    • Use middleware to set user-specific fallbacks:
      public function handle($request, Closure $next) {
          app('translator')->setFallbackLocale($request->user()->preferred_fallback);
          return $next($request);
      }
      

Gotchas and Tips

Pitfalls

  1. JSON File Structure:

    • Pitfall: Non-flat JSON (e.g., arrays/objects as values) will break the package.
      // ❌ Fails: Values are objects
      {"key": {"nested": "value"}}
      
    • Fix: Flatten keys or pre-process files to use dot notation (e.g., key.nested).
  2. Missing Fallback Locale:

    • Pitfall: If a fallback locale (e.g., 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
      
    • Fix: Ensure fallback locales have comprehensive translations or handle missing keys in your app logic.
  3. Service Provider Order:

    • Pitfall: Registering a custom translation provider before JsonFallbackServiceProvider may override the fallback logic.
    • Fix: Ensure JsonFallbackServiceProvider is loaded last in config/app.php.
  4. Caching Issues:

    • Pitfall: Changes to JSON files or fallback config may not reflect immediately due to caching.
    • Fix: Clear caches after updates:
      php artisan config:clear
      php artisan cache:clear
      
  5. Locale Auto-Detection:

    • Pitfall: The package respects Laravel’s default locale detection. If your app uses a non-standard locale detection method (e.g., cookie-based), ensure it’s set before trans() calls.

Debugging

  1. Check Fallback Chain:

    • Log the fallback chain to debug missing translations:
      $translator = app('translator');
      $locale = $translator->getLocale();
      $fallback = $translator->getFallbackLocale();
      logger("Fallback chain: {$locale} → {$fallback}");
      
  2. Validate JSON Files:

    • Use php artisan json-fallback:validate (if the package adds this command) or a custom script to check for malformed JSON.
  3. Override Fallback Temporarily:

    • Test fallbacks by overriding the locale:
      app('translator')->setLocale('fr');
      app('translator')->setFallbackLocale('es');
      trans('json.key'); // Test fallback to 'es'
      

Tips

  1. Partial Translations:

    • Use this package to ship partial translations incrementally. Focus on high-impact keys first (e.g., auth, checkout).
  2. Frontend Consistency:

    • Bundle JSON files for SPAs and ensure they match backend fallbacks. Use the same key structure in both.
  3. Performance:

    • For high-traffic APIs, cache translations:
      $translation = cache()->remember("trans.{$locale}.{$key}", now()->addHours(1), function() use ($locale, $key) {
          return trans($key, [], $locale);
      });
      
  4. Extending Fallbacks:

    • Extend the package to support multi-level fallbacks by modifying 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;
      });
      
  5. CI/CD Validation:

    • Add a script to validate JSON files and fallbacks in your pipeline:
      # 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);' -- {} \;
      
  6. Documentation:

    • Document your JSON key structure and fallback rules for translators/designers to avoid inconsistencies.
  7. Testing Edge Cases:

    • Test with:
      • Missing keys in all locales.
      • Non-existent fallback locales.
      • Malformed JSON (e.g.,
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope