2016-10-19 30 views
0

我用laravel 5.3和setLocale不工作本地化Laravel不工作 「的setLocale ::」

如果我在路由使用setLocate - >不工作,例如:

Route::get('loc/{locale?}', function($locale) { 
App::setLocale($locale); 
return redirect()->back();}); 

但如果我在我的文件路徑中的其他地方使用這個工作! 我在代碼中提及的指示:

$locale = 'en'; 
App::setLocale($locale); 

俄勒我使用的HomeController:

Route::get('loc/{locale}', '[email protected]'); 

在文件中的HomeController:

public function language($locale) 
{ 
    App::setLocale($locale); 
    return redirect()->back(); 
} 

這種方法也不起作用

+1

你有錯誤嗎?如果沒有,在你的控制器中你可以在設置locale後顯示'dd(app() - > getLocale())? – SimonDepelchin

+0

不,我沒有錯誤。 如果我在'setLocate'之後使用'dd(app() - > getLocale())'我看到 - 「en」或者「ru」這就是我選擇的內容,但是我的lengauge不會在網站中改變。 如果我在文件'app.php'中更改lang - >好,我的腳本更改 –

回答

0

事實上,App::setLocale($locale)不會保留您的更改。所以,如果你想更改區域的動態方式,你有兩個選擇:

  1. 添加的語言環境中的URI:ru.example.comexample.com/ru

然後,您可以從請求中捕獲區域設置。

  1. 在數據庫中爲用戶或應用程序保留區域設置。

當你打example.com/ru,這裏會發生什麼:

// HomeController.php 
public function language($locale) 
{ 
    // Validate locale if needed 

    // Update or create the locale in settings table 
    App\Setting::updateOrCreate(['name' => 'locale'], ['value' => $locale]); 

    // Redirect back 
    return redirect()->back(); 
} 

然後在您的App\Providers\AppServiceProvider

// App/Providers/AppServiceProvider.php 
public function boot() 
{ 
    // Get the locale stored in the settings table 
    $locale = App\Setting::where('name', 'locale')->first(); 

    // Setup the app locale 
    app()->setLocale($locale ? $locale->value : config('app.locale')); 
} 

所以你settings表是這樣的:

id | name  | value 
-- | --------- | --------------- 
1 | locale | ru 
2 | timezone | Europe/Brussels 
3 | copyright | @2016 ACME Inc