devwizardhq / laravel-localizer
Laravel Localizer bridges Laravel translations to your SPA frontend (React/Vue/Inertia) and provides generated language assets, type-safe usage, and global translation helpers.
Fund package maintenance!
DevWizard
Installs: 3
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/devwizardhq/laravel-localizer
Requires
- php: ^8.3
- illuminate/contracts: ^11.0||^12.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/framework: ^11.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^9.0
- pestphp/pest: ^3.0
- pestphp/pest-plugin-arch: ^3.0
- pestphp/pest-plugin-laravel: ^3.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
README
Seamlessly bridge Laravel translations to your SPA frontend (React/Vue) with automatic TypeScript generation, type-safe usage, and powerful localization features.
Features
- π Auto-scan translations - Automatically discover translation keys from your codebase
- π Auto-translate - Use Google Translate to automatically translate missing keys
- π¦ TypeScript generation - Export translations as TypeScript files for frontend use
- π― Type-safe - Full IDE support with PHPDoc annotations
- β‘ Performance - In-memory caching and build-time generation
- π Vendor support - Automatically includes translations from vendor packages
- π RTL support - Built-in right-to-left language support
- π¨ Framework agnostic - Works with React, Vue, and vanilla JavaScript
Installation
Install via Composer:
composer require devwizardhq/laravel-localizer
Run the installation command:
php artisan localizer:install
This interactive installer will:
- β Publish configuration file
- β Create default locale files
- β Publish and register middleware
- β Setup TypeScript output directory
- β Generate initial translation files
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:
- Detects user's preferred locale
- Sets the application locale
- Shares locale data with Inertia.js
Locale Detection Priority:
- Query parameter:
?locale=fr - Request header:
X-Locale: fr - Session: stored from previous requests
- User model:
$user->getLocale()(if method exists) - Browser:
Accept-Languageheader - 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:
- JSON keys (no dots):
welcome,hello worldβ stored in{locale}.json - PHP keys (with dots):
validation.required,auth.failedβ stored in{locale}/{file}.php
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:
- Hooks/composables for translations
- Vite plugin for automatic regeneration
- Full TypeScript support
- Inertia.js integration
- Placeholder replacement
- Pluralization support
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.