How can I make the user switch languages in Larave

2019-02-07 17:33发布

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.

标签: laravel-5
2条回答
我只想做你的唯一
2楼-- · 2019-02-07 18:03

Option 1:

  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. When user or guest clicks on a certain language link then update user locale in database or store guest choice in a session

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. 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.

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

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;
    }

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. Lets set the middleware to run on each request by adding it to $middleware stack in App\Http\Kernel.php

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

查看更多
唯我独甜
3楼-- · 2019-02-07 18:06

You can achieve the above by referring to the Laravel documentation, it is the Localization section.

查看更多
登录 后发表回答