如何在Laravel 5中使用户切换语言? [英] How can I make the user switch languages in Laravel 5?

查看:293
本文介绍了如何在Laravel 5中使用户切换语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个双语的laravel 5应用程序,其中包含两个语言环境,即en和ar.

I have created a bilingual laravel 5 application that contains two locales, en and ar.

我希望站点访问者能够通过单击标有语言名称的链接来更改网站的语言.

What I want is for the site visitor to be able to change the language of the website by clicking on a link labeled with the language name.

推荐答案

选项1:

  1. 将用户语言存储在数据库中,我的用户表中有我的语言.这是为了避免在用户每次登录到您的应用程序时询问用户. 您可以将"en"设置为默认值.但是,如果用户是访客,则我们将语言环境存储在会话中.
  1. Store user language in database, I have mine in users table. This is to avoid asking user each time they login to your application. You can set 'en' as default. However if user is a guest we store locale in session.

因此您的迁移可能看起来像这样:

So your migration might look like this:

<?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');
    }

}

  1. 当用户或来宾单击某个语言链接时,然后在数据库中更新用户区域设置或在会话中存储来宾选择

示例: 适用于您的控制器中经过身份验证的用户或访客

Example : For authenticated user or guest in your controller

public function setLocale($locale){
 if(Auth::check()){
     $user = User::find(Auth::user()->id);
     $user->update(['locale'=>$locale]);
  }else{
    Session::put('locale',$locale);
  }
}

  1. 我们需要找到一种在每个请求上设置语言环境的方法,因为Laravel不存储使用App::setLocale()设置的语言环境,因此我们将使用中间件在每个请求上设置setLocale.
  1. We need to find a way of setting locale on each request because Laravel does not store locale set with App::setLocale() hence we are going to use a Middleware to setLocale on each request.

要了解Laravel如何处理App::setLocale(),这里是Illuminate \ Foundation \ Application.php中处理语言环境设置的方法

To understand how Laravel handles App::setLocale() here is the method in Illuminate\Foundation\Application.php that handles setting of locale

    public function setLocale($locale)
    {
        $this['config']->set('app.locale', $locale);

        $this['translator']->setLocale($locale);

        $this['events']->fire('locale.changed', array($locale));
    }

此方法在Translator.php中调用另一个方法,如下所示:

This method calls another method in Translator.php show below:

/**
     * Set the default locale.
     *
     * @param  string  $locale
     * @return void
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;
    }

如您所见,没有什么可以像记住缓存或会话那样记住语言环境的,所以我们必须在每个请求上都设置它.因此,让我们为其创建一个中间件.我将其称为LocaleMiddleware.

As you can see nothing like caching or session is used to remember locale so we must set it on each request. So lets create a Middleware for it. I will call it 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);
    }

}

  1. 通过将中间件添加到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' ];

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' ];

这篇关于如何在Laravel 5中使用户切换语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆