我创建了一个双语 Laravel 5 应用程序,其中包含两个语言环境:en 和 ar。
我想要的是网站访问者能够通过单击标有语言名称的链接来更改网站的语言。
最佳答案
选项 1:
- 将用户语言存储在数据库中,我的用户语言存储在用户表中。这是为了避免用户每次登录您的应用程序时询问用户。 您可以将“en”设置为默认值。但是,如果用户是访客,我们会将区域设置存储在 session 中。
因此您的迁移可能如下所示:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('locale', 5)->default('en');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
- 当用户或访客点击某种语言链接时,会更新数据库中的用户区域设置或在 session 中存储访客选择
示例: 对于 Controller 中经过身份验证的用户或访客
public function setLocale($locale){
if(Auth::check()){
$user = User::find(Auth::user()->id);
$user->update(['locale'=>$locale]);
}else{
Session::put('locale',$locale);
}
}
- 我们需要找到一种在每个请求上设置区域设置的方法,因为 Laravel 不存储使用
App::setLocale()
设置的区域设置,因此我们将使用中间件在每个请求上设置区域设置。
要了解 Laravel 如何处理 App::setLocale()
,这里是 Illuminate\Foundation\Application.php 中处理区域设置的方法
public function setLocale($locale)
{
$this['config']->set('app.locale', $locale);
$this['translator']->setLocale($locale);
$this['events']->fire('locale.changed', array($locale));
}
该方法调用 Translator.php 中的另一个方法,如下所示:
/**
* Set the default locale.
*
* @param string $locale
* @return void
*/
public function setLocale($locale)
{
$this->locale = $locale;
}
正如您所看到的,没有像缓存或 session 这样的东西用于记住区域设置,因此我们必须在每个请求上设置它。因此,让我们为其创建一个中间件。我将其称为 LocaleMiddleware。
<?php namespace App\Http\Middleware;
use Closure, Session, Auth;
class LocaleMiddleware {
public function handle($request, Closure $next)
{
if(Auth::user()){
app()->setLocale(Auth::user()->locale);
}elseif($locale = Session::has('locale')){
app()->setLocale($locale);
}
return $next($request);
}
}
- 让我们将中间件添加到 App\Http\Kernel.php 中的 $middleware 堆栈中,将其设置为在每个请求上运行
protected $中间件 = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'照亮\Cookie\中间件\EncryptCookies',
'照亮\Cookie\中间件\AddQueuedCookiesToResponse',
'照亮\ session \中间件\StartSession',
'照亮\ View \中间件\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'应用程序\Http\中间件\LocaleMiddleware'
];
关于laravel-5 - 如何让用户在 Laravel 5 中切换语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723344/