Laravel 提供了强大的国际化(i18n)功能,可以轻松实现多语言支持。以下是完整的实现步骤:
首先在 config/app.php
中设置默认语言和备用语言:
'locale' => 'en', // 默认语言
'fallback_locale' => 'en', // 备用语言
Laravel 的语言文件存放在 resources/lang
目录下,为每种语言创建单独的子目录:
resources/lang/
en/
messages.php
validation.php
zh-CN/
messages.php
validation.php
ja/
messages.php
validation.php
语言文件返回键值对数组,例如 resources/lang/en/messages.php
:
return [
'welcome' => 'Welcome to our application',
'greeting' => 'Hello, :name',
];
echo __('messages.welcome');
// 或使用辅助函数
echo trans('messages.welcome');
echo __('messages.greeting', ['name' => 'John']);
<h1>{{ __('messages.welcome') }}</h1>
<p>{{ __('messages.greeting', ['name' => $user->name]) }}</p>
创建中间件:
php artisan make:middleware Localization
编辑中间件:
public function handle($request, Closure $next)
{
if (session()->has('locale')) {
app()->setLocale(session()->get('locale'));
}
return $next($request);
}
注册中间件到 Kernel.php
。
Route::get('locale/{locale}', function ($locale) {
if (in_array($locale, ['en', 'zh-CN', 'ja'])) {
session(['locale' => $locale]);
app()->setLocale($locale);
}
return back();
});
Laravel 的验证错误消息也可以本地化。在 resources/lang/xx/validation.php
中定义:
return [
'required' => 'The :attribute field is required.',
// 更多验证消息...
];
使用 Carbon 进行日期本地化:
\Carbon\Carbon::setLocale(app()->getLocale());
如果需要存储用户生成的多语言内容,可以考虑以下方法:
Schema::create('posts', function (Blueprint $table) {
$table->string('title_en');
$table->string('title_zh');
// 其他字段...
});
Schema::create('posts', function (Blueprint $table) {
$table->json('title'); // 存储为 {"en": "Title", "zh": "标题"}
// 其他字段...
});
使用时:
$title = json_decode($post->title, true)[app()->getLocale()];
可以使用 Composer 安装现成的语言包:
composer require caouecs/laravel-lang
public function detectLocale($request)
{
$locale = $request->getPreferredLanguage(config('app.available_locales'));
app()->setLocale($locale);
}
结合 JavaScript 实现无刷新语言切换:
document.getElementById('language-switcher').addEventListener('change', function() {
fetch('/locale/' + this.value)
.then(() => window.location.reload());
});
编写测试确保多语言功能正常工作:
public function testLocaleSwitch()
{
$response = $this->get('/locale/zh-CN');
$response->assertSessionHas('locale', 'zh-CN');
$this->get('/')
->assertSee('欢迎'); // 检查中文内容
}
通过以上步骤,你可以为 Laravel 应用实现完整的多语言支持。根据项目需求,你可以选择适合的方案进行扩展和优化。