Laravel 5 多語系切換

步驟說明:

  1. 建立語系檔
  2. 新增語系 Controller
  3. 指定 route
  4. 新增 Middleware,並設定 Kernel.php

在 /project-folder/resources/lang 底下,建立好語系的目錄。

/project-folder/resources/lang/en (這是預設目錄)
/project-folder/resources/lang/tw
...

分別建立同樣檔名的語系檔。

/project-folder/resources/lang/en/mySite.php
/project-folder/resources/lang/tw/mySite.php

分別寫入同樣名稱的陣列。

en/mySite.php
<?php
return array(
	'siteName' => 'Topias.IM'
);

tw/mySite.php
<?php
return array(
	'siteName' => 'Topias.我手寫我口'
);

在 /project-folder/app/http/Controllers 底下,新增檔案 LocaleController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LocaleController extends Controller {
	public function chooser (Request $request) {
		\Session::put('locale', $request->locale);
		return back();
	}
}

開啟 /project-folder/app/http/routes.php,新增以下規則

Route::post('/locale', array(
	'before' => 'csrf',
	'as' => 'language-chooser',
	'uses' => 'LocaleController@chooser'
));

利用 artisan 新增 Middleware (是說直接手動新增檔案也可以啦)

php artisan make:middleware Locale

會自動產出 /project-folder/app/http/Middleware/Locale.php
接著,程式碼修改如下:

<?php
namespace App\Http\Middleware;

use Closure;
use Session;
use App;
use Config;

class Locale {
    public function handle($request, Closure $next) {
    	$language = Session::get('locale', Config::get('app.locale'));
        App::setLocale($language);
        return $next($request);
    }
}

然後去修改 /project-folder/app/http/Kernel.php,加入剛剛的 Middleware

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        'App\Http\Middleware\Locale',
    ];

最後,將想要加入語系切換 HTML 加上,就完成了。

<form method="post" action="{{ URL::route('language-chooser') }}">
	<select name="locale">
		<option value="en">English</option>
		<option value="tw"{{ Session::get('locale') === "tw" ? " selected" : "" }}>中文</option>
	</select>
	<input type="submit" value="Choose">
	<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

使用的時候也很簡單:

<div class="title">{{ trans('mySite.siteName') }}</div>

參考文章:

  1. https://www.youtube.com/watch?v=FpXk_8aU1bU
  2. http://stackoverflow.com/questions/30481158/laravel-5-changing-locale-middleware-via-menuitiem-jquery-controller-middlewa