Laravel 5多国语言不起作用 [英] Laravel 5 multi language not working
问题描述
我试图本地化我的应用程序,但似乎缺少了一些东西.我以前对此没有任何了解,因此很难入门.这是我的routes.php
I tried to localization my app, but seems like I'm missing something. I don't have any previous knowledge about this and therefore it's pretty hard to get started. Here is my routes.php
Route::get('/lang/{lang}', 'LangController@index');
这是我的LangController.php
And here is my LangController.php
public function index($lang)
{
$langs =['en', 'de'];
if(in_array($lang, $langs)){
Session:set('lang', $lang);
return Redirect::back();
}
}
我在中间件中设置:(Lang.php)
I set in middleware:(Lang.php)
public function handle($request, Closure $next)
{
if($lang = Session::get('lang')){
\Lang::setLocale($lang);
}
return $next($request);
}
在Http \ Kernel.php中启用它:
Enable it in Http\Kernel.php:
protected $middleware = [
\App\Http\Middleware\Lang::class,
\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,
];
在我的blade.php中
In my blade.php
{{ Lang::get('home.hello')}}
CURRENT: {{ Lang::getLocale() }} <br /> <br />
<a href="{{ url('lang/de') }}">Germany</a> | <a href="{{ url('lang/en') }}">English</a>
请帮助.我看不到我想念的东西... 在字段CURRENT中,按德国时应为"de",按英语时应为"en",但按德国时仍为"en" ...(默认为"en" config/app.php->"locale" '=>'en',)
Please help.I do not see what I missing... In field CURRENT when press Germany it shoul be 'de' and when press English it shoul be 'en' but when press Germany it still stay 'en'... (default is 'en' config/app.php -> 'locale' => 'en',)
推荐答案
由于您正在中间件中使用会话,因此,所需的值将在StartSession
中间件设置会话之前不可用.
Because you are using the session in your middleware, the values you need will not be available until the StartSession
middleware sets up the session.
因此,您应该在此之后将中间件添加到某处,就像这样:
So you should add your middleware somewhere after that, like so:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, // Init session
\App\Http\Middleware\Lang::class, // Set locale
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
除此之外,您的控制器代码中还存在一个小的语法错误.在将值分配给index
控制器方法中的会话时,您忘记为范围解析运算符添加第二个冒号(:
).因此:
Aside from that you also have a small syntax error in your controller code. You forgot to add the second colon (:
) for the scope resolution operator, when assigning the value to the session in your index
controller method. So this:
Session:set('lang', $lang);
应该是这样
Session::set('lang', $lang);
这篇关于Laravel 5多国语言不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!