选项1:
- 将用户语言存储在数据库中,我的用户语言存储在用户表中。这是为了避免用户每次登录您的应用程序时询问用户。
您可以将“en”设置为默认值。但是,如果用户是访客,我们会将区域设置存储在会话中。
所以你的迁移可能看起来像这样:
<?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');
}
}
- 当用户或访客单击某种语言链接时,更新数据库中的用户区域设置或将访客选择存储在会话中
例子 :
对于控制器中经过身份验证的用户或访客
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()
因此我们将使用中间件在每个请求上设置Locale。
了解 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;
}
正如您所看到的,没有像缓存或会话这样的东西可以用来记住区域设置,因此我们必须在每个请求上设置它。因此,让我们为其创建一个中间件。我将其称为 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 $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\LocaleMiddleware'
];