Laravel本地化不起作用:区域设置未更改

8iwquhpp  于 2023-02-25  发布在  其他
关注(0)|答案(2)|浏览(163)

我试图使本地化与Laravel,但我的代码不工作,一些意见或建议?
下面是代码:

    • 我的Language中间件handle()方法:**
public function handle($request, Closure $next)
{
    if(Session::has('locale')) {
        $locale = Session::get('locale', Config::set('app.locale'));
    } else {
        $locale = "bg";
    }

    App::setLocale($locale);

    return $next($request);
}
    • 我的控制器方法:**
public function changeLang(Request $request,$lang) {
    if (!empty($request)) {
        Session::put('locale',$lang);
    } else {
        Session::set('locale',$lang);
    }
    return back();
}

这是我的路线:

Route::get('/{lang}','LanguageController@changeLang');

我哪里做错了?

qnakjoqk

qnakjoqk1#

希望这段代码对你有用。

    • 主计长**
public function index($locale) 
  {
      session(['locale' => $locale]);
      App::setLocale($locale);
      return Redirect::back();
   }
    • 语言中间件:**
public function handle($request, Closure $next)
    {
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }
        else { // This is optional as Laravel will automatically set the fallback language if there is none specified
            App::setLocale(Config::get('app.fallback_locale'));
        }
        return $next($request);
    }
    • 路线:**
Route::get('/{lang}', 'LanguageController@index');

最后将您的语言中间件添加到middlewaregroup中的app/Http/Kernal. php

\App\Http\Middleware\Language::class,
olmpazwi

olmpazwi2#

我通过在中间件组中添加我的中间件修复了它!

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\Language::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

相关问题