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
 'Topias.IM'
);

tw/mySite.php
 'Topias.我手寫我口'
);

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

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
接著,程式碼修改如下:


然後去修改 /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 加上,就完成了。

使用的時候也很簡單:

{{ trans('mySite.siteName') }}

參考文章:

  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