【问题标题】:Laravel 5.4 Locale restores to default when using redirect()使用 redirect() 时 Laravel 5.4 语言环境恢复为默认值
【发布时间】:2018-01-08 11:55:54
【问题描述】:

我在 Fresh new Project 中遇到了 Laravel 的语言环境问题。我用谷歌搜索了很多次,但他们没有解决我的问题。

然后我关注locale in laravel 5.4 returns to the pervious locale after refresh源,但只有当我通过view

调用页面时它才有效
  return view('home');

当我使用路由

时它不起作用
  return redirect()->route('home');

这是我的文件:

web.php

Route::get('/lang/{locale}', function ($locale) {
    App::setLocale($locale);
    Session::put('locale', $locale);
    //return view('home');                         ###### This one works
    return redirect()->route('home');              ###### Where as this does NOT work
});

Route::get('/', function () {
    return view('welcome');
});

Route::get('/home', 'HomeController@index')->name('home');

home.blade.php

<div class="panel-body">
    You are logged in!
    {{__('auth.success')}}
    <br>
    <a href="/lang/ru">Rus</a>
    <br>
    <a href="/lang/kg">Kgz</a>
</div>

ChangeLocale.php 中间件(我为每个页面请求调用它)

public function handle($request, Closure $next)
{
    if(Session::has('locale')) {
        app()->setLocale(Session::get('locale'));
    }
    return $next($request);
}

提前致谢;)

好的,我改完之后

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/home', 'HomeController@index')->name('home')->middleware('changeLocale');

它开始起作用了。

那么,为什么我的中间件不起作用?

我应该将中间件分别分配给我的所有路由吗?

【问题讨论】:

  • 创建一个路由组,将中间件应用于lang/{locale}以外的路由。

标签: redirect routes localization laravel-5.4


【解决方案1】:

您可以将您的changeLocale 中间件添加到web 组中的app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        ...
        \Your\ChangeLocateMiddleware::class
    ],
    ...
]

正如您在app/Providers/RouteServiceProvider.php 中所见,此中间件组适用于您的所有web 路由。

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2011-10-29
    • 2016-09-07
    • 2014-03-31
    • 1970-01-01
    相关资源
    最近更新 更多