Laravel+Cookie+ route parameters實現多國語言網路識別

in laravel •  7 years ago  (edited)

Laravel提供了一個文件夾檢索/resources/lang供我們開發多國語的應用。但官方文檔範例只提供一條路由定向作為多國語言:

Route::get('welcome/{locale}', function ($locale) {
    App::setLocale($locale);
});

基於上例,假設你的網址為http://localhost/,英文語言代碼為en,中文語言代碼為cn。那你要在網址列輸入http://localhost/welcome/en,Laravel識別語言為英語。相同地,輸入http://localhost/welcome/cn,則識別語言為中文。
但是,簡單的一條路由定向並不能我們日常的應用,所以配合、方便大家的應用。

設計思路:

  • 統一接口管理
  • 硬性規定URL帶有語言代碼
  • 可供存取瀏覽用戶的語言設定
  • 判斷所獲取的語言代碼合法性

解決方案:

  • Route設定/{lang?}作為統一語言定向接口
  • 用Middlewave作獲取的語言代碼、判斷合法性、以及糾正定向。
  • 以Cookie儲存瀏覽用戶之語言設定

操作步驟:

  1. Terminall執行以下命令:
php artisan make:middleware getLanguage
  1. 用以下代碼取替/app/Http/Middleware/getLanguage.php內容
<?php

namespace App\Http\Middleware;

use Closure;
use Cookie;

class getLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){

        $language = '';
        $cookieLanguage = $request->cookie('lang');
        $paramLanguage = $request->route()->parameter('lang');
        $envLanguage = config('app.locale');

        if(!empty($paramLanguage)){
            $language = $paramLanguage;
        }else{
            if(!empty($cookieLanguage)){
                $language = $cookieLanguage;
            }else{
                $language = $envLanguage;
            }

        }

        if(!file_exists(base_path().'/resources/lang/'.$language)){
            if(!empty($cookieLanguage) and $language != $cookieLanguage){
                $language = $cookieLanguage;
            }else if(!epmty($paramLanguage) and $language != $paramLanguage){
                $language = $paramLanguage;
            }else if(!empty($envLanguage) and $language != $envLanguage){
                $language = $envLanguage;
            }
        }

        if($language != $cookieLanguage){
            Cookie::queue('lang', $language, 1000*60*60*24*365);
        }

        if($language != $paramLanguage){
            return redirect('/'.$language);
        }

        return $next($request);
    }
}
  1. 於/app/Http/Kernel.php內的$routeMiddleware數組內增加以下:
'language' => \App\Http\Middleware\getLanguage::class,
  1. 於/routes/web.php裡增加以下代碼:
Route::group(['middleware' => ['language']], function () {

    Route::get('/{lang?}', function ($lang = null) {
        App::setLocale($lang);
        //return view('welcome');
    });
});

自定義

新增語言

於/resources/lang內新增資料夾,資料夾名稱為語言代碼。

新增需要讀取語言設定的路由指向:

於/routes/web.php內的

Route::group(['middleware' => ['language']], function () {

    //例如:   
    Route::get('/{lang?}/welcome', function ($lang = null) {
        //設定語言
        App::setLocale($lang);
    });

    //例如:   XXX為你的路由目標
    Route::get('/{lang?}/XXX', function ($lang = null) {
        //設定語言
        App::setLocale($lang);
    });
}

聯絡我

如果在使用上遇到難題或有更好的建議,歡迎你隨時與我聯繫,衷心等待你的來信。

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Congratulations @kanelau! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You published your First Post
You made your First Vote
You got a First Vote

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard!


Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes


Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @kanelau! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @kanelau! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!