语言区域设置不会随App :: setLocale而改变,而是在laravel 5.2中更新Session :: put()

时间:2016-02-05 13:23:21

标签: php laravel laravel-5 multilingual

我正在为我的laravel应用程序提供多语言支持,所有在网上看到的材料都表示将语言环境传递给App外观并调用setLocale方法翻译网站,我已经尝试过但没有运气。

在我的路线文件中,我有这个

Route::group(['middleware' => ['web']], function () {
  Route::get('change-locale', ['uses' => 'HomeController@changeLocale', 'as' => 'locale.change']);
});

HomeController @ changeLocale我有......

namespace Gudaapp\Http\Controllers;
use Illuminate\Http\Request;

use Gudaapp\Http\Requests;
use Gudaapp\Http\Controllers\Controller;
class HomeController extends Controller
{
public function changeLocale(Request $request) {
    if(empty($request->locale)) { redirect()->back()->withMessage('Unknown locale, please, if problem persists, contact admin.'); }
    session()->put('locale', $request->locale);
    return redirect()->back()->withMessage('Your locale has now been changed to <b>'.$request->locale.'</b>')->withMessageType('success');
}
}

并在发送请求的视图中..

<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
   @foreach(config('app.languages') as $locale => $lang)
       <li class="{{ session('locale') == $locale ? 'active' : '' }}">
           <a href="{!! route('locale.change', ['locale'=> $locale]) !!}" ><img src='{!! asset($lang["flag"]) !!}' alt="" />&nbsp;{{ $lang['language'] }}</a>
        </li>
  @endforeach
</ul>

我总是收到成功的通知,但App :: getLocale()仍然是默认值,因此网站无法翻译。我需要帮助。

1 个答案:

答案 0 :(得分:0)

您是否还在应用程序启动时从会话中配置区域设置? 您可以在服务提供程序的引导方法中执行此操作,例如:

// app/Providers/AppServiceProvider.php
public function boot()
{
    $locale = $this->app['session']->get('locale'); // This would be the same as session()->get(... and Session::get(...
    $this->app->setLocale($locale); // This would also equal app()->setLocale(... and App::setLocale(...
}

您可能需要在此处执行一些额外操作以确保区域设置有效。