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

Laravel Js Localization Laravel Package

mariuzzo/laravel-js-localization

Export Laravel translation files to JavaScript. Generate a JS bundle (with Lang.js) via artisan to use familiar Laravel-style trans() and pluralization on the frontend. Supports Laravel 4.2 through 8.x, with options to choose files and output path.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mariuzzo/laravel-js-localization
    

    Publish the config file:

    php artisan vendor:publish --provider="Mariuzzo\LaravelJsLocalization\LaravelJsLocalizationServiceProvider" --tag="config"
    
  2. Basic Configuration Edit config/js-localization.php to define your locales and paths:

    'locales' => [
        'en' => 'en',
        'es' => 'es',
    ],
    'paths' => [
        'en' => resource_path('lang/en.json'),
        'es' => resource_path('lang/es.json'),
    ],
    
  3. First Use Case: Localized Strings in Blade

    @jsLocalization(['greeting' => 'Hello'])
    

    Access in JavaScript:

    const greeting = @json($jsLocalization['greeting']);
    
  4. First Use Case: Full Locale Integration

    @jsLocalization(['locale' => 'es'])
    

    Access in JavaScript:

    const translations = @json($jsLocalization);
    console.log(translations.greeting); // 'Hola' (if defined in es.json)
    

Implementation Patterns

1. Locale-Specific Translations

  • Workflow: Use the @jsLocalization directive in Blade to pass locale-specific translations to JavaScript.
    @jsLocalization(['locale' => app()->getLocale()])
    
  • JavaScript Access:
    const { greeting, error } = @json($jsLocalization);
    

2. Dynamic Locale Switching

  • Workflow: Update the locale dynamically via AJAX or user interaction.
    async function switchLocale(locale) {
        const response = await fetch(`/api/locale?locale=${locale}`);
        const data = await response.json();
        window.jsLocalization = data; // Update global object
    }
    
  • Backend Handling (in a controller):
    public function switchLocale(Request $request) {
        $request->session()->put('locale', $request->locale);
        return response()->json([
            'locale' => $request->locale,
            'translations' => $this->getTranslations($request->locale),
        ]);
    }
    

3. Integration with Vue/React

  • Vue Example:
    export default {
        data() {
            return {
                translations: @json($jsLocalization),
            };
        },
        methods: {
            getTranslation(key) {
                return this.translations[key] || key;
            },
        },
    };
    
  • React Example:
    const translations = @json($jsLocalization);
    const App = () => <div>{translations.greeting}</div>;
    

4. Fallback Locales

  • Configure fallback locales in config/js-localization.php:
    'fallbackLocales' => [
        'es' => 'en',
        'fr' => 'en',
    ],
    
  • Usage: If a translation is missing in es.json, it falls back to en.json.

5. Custom Translation Paths

  • Override paths per locale dynamically:
    $paths = [
        'en' => storage_path('app/lang/custom/en.json'),
        'es' => storage_path('app/lang/custom/es.json'),
    ];
    config(['js-localization.paths' => $paths]);
    

Gotchas and Tips

Pitfalls

  1. Caching Issues

    • If translations aren’t updating, clear the view cache:
      php artisan view:clear
      
    • Ensure cache.jsLocalization is set to false in config/js-localization.php during development.
  2. Locale Mismatch

    • Verify that the locale in app()->getLocale() matches the expected JSON file (e.g., es vs. es_ES).
  3. JSON Syntax Errors

    • Validate your JSON files for syntax errors. Use a linter or online validator.
  4. Missing Translations

    • If a key is missing, the package returns the key itself (e.g., {{ __('missing_key') }} outputs missing_key). Use fallback locales or default values:
      const message = translations.someKey || 'Default Message';
      
  5. Blade Directive Scope

    • The @jsLocalization directive must be placed before any JavaScript that uses the translations. Avoid nesting it inside conditional Blade directives if the JS runs unconditionally.

Debugging Tips

  1. Inspect Output Dump the generated JSON to verify content:

    @php
        dd($jsLocalization);
    @endphp
    
  2. Check Config Verify config/js-localization.php paths and locales:

    dd(config('js-localization'));
    
  3. Network Tab Inspect the HTTP response in Chrome DevTools to ensure translations are being passed correctly.

Extension Points

  1. Custom Translation Loader Extend the package by binding a custom loader:

    use Mariuzzo\LaravelJsLocalization\Loaders\TranslationLoaderInterface;
    
    class CustomLoader implements TranslationLoaderInterface {
        public function load($locale) {
            return json_decode(file_get_contents("custom/path/{$locale}.json"), true);
        }
    }
    
    // Register in a service provider:
    app()->bind(TranslationLoaderInterface::class, function () {
        return new CustomLoader();
    });
    
  2. Middleware for Locale Force a locale for specific routes:

    public function handle($request, Closure $next) {
        app()->setLocale('es');
        return $next($request);
    }
    
  3. Pluralization Support Use Laravel’s built-in pluralization helpers in JSON files:

    {
        "messages": {
            "one": "One item",
            "many": ":count items"
        }
    }
    

    Access in JavaScript:

    const count = 5;
    const message = @json($jsLocalization.messages).replace(':count', count);
    
  4. Interpolation Use placeholders in JSON (e.g., "welcome": "Welcome, :name!") and replace them in JavaScript:

    const name = 'John';
    const welcome = translations.welcome.replace(':name', name);
    
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.
terminal42/code-quality-tools
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