更新。 我想知道如何在会话中设置语言环境。
我的语言选择器不是'输入类型,但只是文本。这是刀片片段 - 这是语言选择器:
<div class = "col-lg-5 col-md-5" id = "lang">
<ul id = "lang_menu">
<li class = "language active">Latviešu</a></li>
<li class = "language">Pусский</a></li>
<li class = "language">English</a></li>
</ul>
</div>
以下是路线:
Route::get('/', 'PagesController@index');
Route::get('/mafia', 'PagesController@mafia');
Route::get('/games', 'PagesController@games');
Route::get('/discounts', 'PagesController@discounts');
Route::get('/tournaments', 'PagesController@tournaments');
Route::get('/gallery', 'PagesController@gallery');
Route::get('/aboutus', 'PagesController@aboutus');
我也有transladet文件,当我在config
中更改语言环境时,它工作正常&LT;&LT; ----------修订-----------------&GT;&GT;
现在我到目前为止但仍然无法正常工作。我从一个教程中创建了这个代码。我做了同样的事情而且没有用。
这是lang选择Blade:
<ul id = "lang_menu">
<li class = "language active"><a href ="{{ url('/locale/lv') }}">Latviešu</a></li>
<li class = "language"><a href ="{{ url('/locale/ru') }}">Pусский</a></li>
<li class = "language"><a href ="{{ url('/locale/en') }}">English</a></li>
</ul>
这是路线:
Route::get('locale/{locale?}', array('as'=>'set-locale', 'uses'=>'LanguageController@setLocale'));
这是我的LanguageController:
use Illuminate\Http\Request;
use Session;
use URL;
class LanguageController extends Controller
{
public function setLocale($locale='en'){
if (!in_array($locale, ['en', 'ru', 'lv'])){
$locale = 'en';
}
Session::put('locale', $locale);
return redirect(url(URL::previous()));
}
}
这是中间件&#34; Locale&#34;:
use Closure;
use Session;
use Config;
use App;
class Locale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$locale=Session::get('locale', Config::get('app.locale'));
App::setLocale($locale);
return $next($request);
}
}
并在Kernel.php中添加:
\App\Http\Middleware\Locale::class,
\Illuminate\Session\Middleware\StartSession::class,
答案 0 :(得分:1)
在中间件中,您必须使用从 request 获得的会话,而不是从helper session()或Session :: get()!
public function handle($request, Closure $next)
{
if ($request->session()->has('locale') ) {
$locale = $request->session()->get('locale');
App::setLocale($locale);
}
return $next($request);
}
答案 1 :(得分:0)
您可以设置路由以配置区域设置(请参阅Configuring The Locale),然后重定向回上一个网址:
Route::get('locale/{locale}', function ($locale) {
$validLocale = in_array($locale, ['lv', 'ru', 'en']);
if ($validLocale) {
App::setLocale($locale);
}
return back();
});
当访问者选择区域设置时,请让用户访问您的路线:
<div class = "col-lg-5 col-md-5" id = "lang">
<ul id = "lang_menu">
<li class = "language{{ App::isLocale('lv') ? ' active' : '' }}"><a href="/locale/lv">Latviešu</a></li>
<li class = "language{{ App::isLocale('ru') ? ' active' : '' }}"><a href="/locale/ru">Pусский</a></li>
<li class = "language{{ App::isLocale('en') ? ' active' : '' }}"><a href="/locale/en">English</a></li>
</ul>
</div>