laravel-localizer

Laravel Localizer

Latest Version on Packagist Total Downloads

Seamlessly bridge Laravel translations to your SPA frontend (React/Vue) with automatic TypeScript generation, type-safe usage, and powerful localization features.

Features

Installation

Install via Composer:

composer require devwizardhq/laravel-localizer

Run the installation command:

php artisan localizer:install

This interactive installer will:

Manual Setup

If you prefer manual configuration:

# Publish config
php artisan vendor:publish --tag="laravel-localizer-config"

# Publish middleware
php artisan vendor:publish --tag="laravel-localizer-middleware"

Register the middleware in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \App\Http\Middleware\LocalizerMiddleware::class,
    ]);
})

Quick Start

1. Configure Available Locales

Edit config/localizer.php:

return [
    'default' => 'en',
    'fallback' => 'en',
    
    'available' => [
        'en' => ['label' => 'English', 'flag' => 'πŸ‡¬πŸ‡§', 'dir' => 'ltr'],
        'fr' => ['label' => 'FranΓ§ais', 'flag' => 'πŸ‡«πŸ‡·', 'dir' => 'ltr'],
        'ar' => ['label' => 'Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©', 'flag' => 'πŸ‡ΈπŸ‡¦', 'dir' => 'rtl'],
    ],
    
    'path' => lang_path(),
    'typescript_output_path' => resource_path('js/lang'),
];

2. Sync Translation Keys

Scan your codebase for translation keys:

php artisan localizer:sync --all

This finds all __(), trans(), and lang() calls and adds missing keys to your language files.

3. Generate TypeScript Files

Export translations for your frontend:

php artisan localizer:generate --all

Generates TypeScript files in resources/js/lang/:

// resources/js/lang/en.ts
export const en = {
  "welcome": "Welcome",
  "validation.required": "This field is required"
} as const;

4. Use in Frontend

Install the corresponding frontend package:

# For React
npm install @devwizard/laravel-localizer-react

# For Vue
npm install @devwizard/laravel-localizer-vue

See the React package README or Vue package README for frontend integration details.

Usage

Commands

Sync Translation Keys

# Sync all locales
php artisan localizer:sync --all

# Sync specific locales
php artisan localizer:sync --locales=en,fr

# Interactive selection
php artisan localizer:sync

Auto-translate

Automatically translate from one locale to another using Google Translate:

# With options
php artisan localizer:translate --source=en --target=fr

# Interactive selection
php artisan localizer:translate

Note: Requires stichoza/google-translate-php:

composer require stichoza/google-translate-php

Generate TypeScript Files

# Generate all locales
php artisan localizer:generate --all

# Generate specific locales
php artisan localizer:generate --locales=en,fr

# Interactive selection
php artisan localizer:generate

Programmatic API

use DevWizard\Localizer\Facades\Localizer;

// Create a new locale
Localizer::create('fr', fromLocale: 'en');

// Get all translations (JSON + PHP combined)
$translations = Localizer::get('en');

// Get JSON translations only
$jsonTranslations = Localizer::getJson('en');

// Set a JSON translation
Localizer::set('welcome', 'Welcome!', 'en');

// Set nested PHP translation
Localizer::setPhp('validation.required', 'Field is required', 'en');

// Bulk operations
Localizer::bulkSet([
    'hello' => 'Hello',
    'goodbye' => 'Goodbye',
], 'en');

// Check if translation exists
if (Localizer::has('welcome', 'en')) {
    // ...
}

// Get available locales
$locales = Localizer::availableLocales(); // ['en', 'fr', 'ar']

// Delete a locale
Localizer::delete('fr');

// Rename a locale
Localizer::rename('en', 'en-US');

Middleware

The LocalizerMiddleware automatically:

Locale Detection Priority:

  1. Query parameter: ?locale=fr
  2. Request header: X-Locale: fr
  3. Session: stored from previous requests
  4. User model: $user->getLocale() (if method exists)
  5. Browser: Accept-Language header
  6. Default: config('localizer.default')

Shared Inertia Props:

{
  locale: {
    current: 'en',
    dir: 'ltr',
    available: {
      en: { label: 'English', flag: 'πŸ‡¬πŸ‡§', dir: 'ltr' },
      fr: { label: 'FranΓ§ais', flag: 'πŸ‡«πŸ‡·', dir: 'ltr' },
      ar: { label: 'Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©', flag: 'πŸ‡ΈπŸ‡¦', dir: 'rtl' }
    }
  }
}

Translation Organization

The package uses dot notation to organize translations:

Example structure:

lang/
β”œβ”€β”€ en.json                 # Simple translations
β”œβ”€β”€ en/
β”‚   β”œβ”€β”€ validation.php      # Validation messages
β”‚   └── auth.php           # Auth messages
β”œβ”€β”€ fr.json
└── fr/
    β”œβ”€β”€ validation.php
    └── auth.php

Deployment

Generated Files

The installer automatically adds generated TypeScript files to .gitignore. In your deployment process, regenerate them:

# After composer install
php artisan localizer:generate --all

# Then build frontend
npm run build

Example CI/CD

#!/bin/bash

composer install --no-dev --optimize-autoloader
npm ci

# Generate translations before building
php artisan localizer:generate --all

npm run build
php artisan config:cache
php artisan route:cache
php artisan view:cache

Frontend Packages

Both packages provide:

Configuration

The config/localizer.php file provides extensive customization options:

return [
    // Default and fallback locales
    'default' => env('APP_LOCALE', 'en'),
    'fallback' => env('APP_FALLBACK_LOCALE', 'en'),
    
    // Available locales with metadata
    'available' => [
        'en' => ['label' => 'English', 'flag' => 'πŸ‡¬πŸ‡§', 'dir' => 'ltr'],
    ],
    
    // Paths
    'path' => lang_path(),
    'typescript_output_path' => resource_path('js/lang'),
    
    // Scanning configuration
    'scan' => [
        'include' => [app_path(), resource_path(), base_path('routes')],
        'exclude' => [base_path('vendor'), base_path('node_modules')],
        'extensions' => ['php', 'blade.php', 'js', 'jsx', 'ts', 'tsx', 'vue'],
    ],
];

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.