tooinfinity/lingua
Composer 安装命令:
composer require tooinfinity/lingua
包简介
Zero-config localization for Laravel 12 with Inertia.js and React
README 文档
README
⚠️ Under Development: This package is currently under active development and is not ready for production use.
Share Laravel translations with your Inertia.js + React frontend.
Quick Start
1. Install
composer require tooinfinity/lingua php artisan lingua:install
This installs the Laravel package, publishes the config, and installs the React package (@tooinfinity/lingua-react).
2. Configure Locales
Edit config/lingua.php:
'locales' => ['en', 'fr', 'es'],
3. Middleware
The middleware is auto-registered to the web group by default. No action needed for most apps.
To disable auto-registration and add manually:
// config/lingua.php 'middleware' => [ 'auto_register' => false, ], // bootstrap/app.php ->withMiddleware(function (Middleware $middleware) { $middleware->web(append: [ \TooInfinity\Lingua\Http\Middleware\LinguaMiddleware::class, ]); })
4. Create Translations
lang/
├── en/
│ └── messages.php
└── fr/
└── messages.php
// lang/en/messages.php return [ 'welcome' => 'Welcome!', 'greeting' => 'Hello, :name!', ]; // lang/fr/messages.php return [ 'welcome' => 'Bienvenue!', 'greeting' => 'Bonjour, :name!', ];
5. Use in React
import { useTranslations } from '@tooinfinity/lingua-react'; function Welcome() { const { __, locale, locales } = useTranslations(); return ( <div> <h1>{__('messages.welcome')}</h1> <p>{__('messages.greeting', { name: 'John' })}</p> <p>Current: {locale}</p> </div> ); }
Locale Switching
import { router } from '@inertiajs/react'; import { useTranslations } from '@tooinfinity/lingua-react'; function LocaleSwitcher() { const { locale, locales } = useTranslations(); const switchLocale = (newLocale: string) => { router.post('/locale', { locale: newLocale }); }; return ( <div> {locales.map((loc) => ( <button key={loc} onClick={() => switchLocale(loc)} disabled={loc === locale} > {loc.toUpperCase()} </button> ))} </div> ); }
Translation Groups (Optional)
Load only the translations needed for a specific request by passing group names to the middleware. When no groups are provided, Lingua shares all translations.
Route::middleware(['web', 'lingua:common,validation'])->get('/dashboard', function () { // ... });
You can also load specific groups manually via Lingua::translationsFor(['common', 'validation']).
API Reference
useTranslations() Hook
const { __, locale, locales, direction, isRtl } = useTranslations(); __('messages.welcome') // "Welcome!" __('messages.greeting', { name: 'John' }) // "Hello, John!"
| Property | Type | Description |
|---|---|---|
__ |
function |
Translation function |
locale |
string |
Current locale |
locales |
string[] |
Supported locales |
direction |
'ltr' | 'rtl' |
Text direction |
isRtl |
boolean |
Is RTL locale |
Facade
use TooInfinity\Lingua\Facades\Lingua; Lingua::getLocale(); // Get current locale Lingua::setLocale('fr'); // Set locale (optionally persists cookie) Lingua::supportedLocales(); // Get supported locales Lingua::translations(); // Get all translations (missing keys fall back to default locale)
Fallback Locale Behavior
When a translation key is missing in the current locale, Lingua automatically fills it from the default locale. This applies to:
- PHP translation groups loaded via
Lingua::translationGroup()andLingua::translations() - JSON translations loaded via
Lingua::translations()whentranslation_driverisjson
If the current locale already matches the default locale, no fallback merge occurs.
// config/lingua.php 'default' => 'en',
// lang/en/auth.php return [ 'login' => 'Login', 'logout' => 'Logout', ]; // lang/fr/auth.php return [ 'login' => 'Connexion', ]; Lingua::setLocale('fr'); // 'logout' comes from the default locale Lingua::translationGroup('auth'); // ['login' => 'Connexion', 'logout' => 'Logout']
Routes
| Method | URI | Description |
|---|---|---|
| POST | /locale |
Switch locale |
Note: The route prefix can be configured via
config('lingua.routes.prefix').
Translation File Formats
Lingua supports both PHP and JSON translation files. Configure the driver in config/lingua.php:
'translation_driver' => 'php', // or 'json'
PHP Translations (Default)
PHP translations are organized in groups (files) under lang/{locale}/:
lang/
├── en/
│ ├── messages.php
│ └── validation.php
└── fr/
├── messages.php
└── validation.php
// lang/en/messages.php return [ 'welcome' => 'Welcome!', 'greeting' => 'Hello, :name!', ];
Shared to React as:
{
"messages": {
"welcome": "Welcome!",
"greeting": "Hello, :name!"
},
"validation": { ... }
}
Access in React: __('messages.welcome')
JSON Translations
JSON translations use a flat key-value structure in lang/{locale}.json:
lang/
├── en.json
└── fr.json
// lang/en.json { "Welcome!": "Welcome!", "Hello, :name!": "Hello, :name!", "auth.login": "Login", "auth.logout": "Logout" }
Shared to React as-is (flat structure):
{
"Welcome!": "Welcome!",
"Hello, :name!": "Hello, :name!",
"auth.login": "Login",
"auth.logout": "Logout"
}
Access in React: __('Welcome!') or __('auth.login')
Tip: JSON translations are ideal for simple apps or when using Laravel's
__()helper with literal string keys.
Advanced
Custom Controller
// config/lingua.php 'controller' => \App\Http\Controllers\LocaleController::class,
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Validation\Rule; use TooInfinity\Lingua\Lingua; class LocaleController { public function __invoke(Request $request, Lingua $lingua) { $validated = $request->validate([ 'locale' => ['required', 'string', Rule::in($lingua->supportedLocales())], ]); $lingua->setLocale($validated['locale']); return redirect()->route('dashboard'); } }
License
MIT License. See LICENSE.md.
tooinfinity/lingua 适用场景与选型建议
tooinfinity/lingua 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「i18n」 「laravel」 「localization」 「react」 「rtl」 「inertia」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 tooinfinity/lingua 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 tooinfinity/lingua 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 tooinfinity/lingua 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Easy to use i18n translation PHP class for multi-language websites
Package for convenient work with Laravel's localization features
Field for number with restricted count of digits and decimal places
A custom URL rule class for Yii 2 which allows to create translated URL rules
Deepl Automated translations for Laravel lang files
Bureaux A Partager Edit - Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
统计信息
- 总下载量: 2
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 25
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-16