Laravel 10.x 本地化无法使用会话工作

问题描述 投票:0回答:1

我在互联网上尝试了几个教程,但它不起作用或语言没有改变,我已经将翻译存储到

\lang
目录中,并且会话已经设置Localization Session

这是我的源代码:

这是我的控制器:

class LocalizationController extends Controller
{
    public function setLang($locale)
    {
        App::setLocale($locale);
        Session::put("locale", $locale);

        return redirect()->back();
    }
}

这是我的中间件:

class LocalizationMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Session::get("locale") != null) {
            App::setLocale(Session::get("locale"));
        } else {
            Session::put("locale", "en");
            App::setLocale(Session::get("locale"));
        }

        return $next($request);
    }
}

这是路线:

Route::get("locale/{lang}", [LocalizationController::class, 'setLang']);

语言切换器:

<a href="{{ url('locale/id') }}"><img class="h-5 mt-4" src="{{ asset('images/flag/id_flag.png') }}"
                alt=""></a>
        <a href="{{ url('locale/en') }}"><img class="h-5 mt-4" src="{{ asset('images/flag/uk_flag.png') }}"
                alt=""></a>

翻译元素:

<h1 class="font-black lg:text-5xl md:text-4xl text-3xl md:w-[500px] mx-auto">{{ __('home.hero.header') }}</h1>

我尝试了网上的一些教程,请帮忙。

php laravel localization laravel-blade laravel-10
1个回答
0
投票

检查语言文件:确保 resources/lang 目录中具有每种支持的语言所需的语言文件。例如,您应该有 en 和 id 目录,其中包含 messages.php 等语言文件。

语言文件中的命名空间:确保语言文件中的翻译使用正确的命名空间。翻译文件中的密钥应与您在视图中使用的密钥相匹配:

例如,如果您的视图有:

{{ __('home.hero.header') }}

那么你的 resources/lang/en/messages.php 文件应该有:

'home' => [
    'hero' => [
        'header' => 'Your translated text here',
    ],
],

清除缓存:如果您对语言文件或配置进行了更改,请清除缓存以确保更改生效。

php artisan 缓存:清除

// Inside LocalizationController
public function setLang($locale)
{
    App::setLocale($locale);
    Session::put("locale", $locale);
    dd(Session::get("locale")); // Debug output
    return redirect()->back();
}

// Inside LocalizationMiddleware
public function handle(Request $request, Closure $next): Response
{
    if (Session::get("locale") != null) {
        App::setLocale(Session::get("locale"));
    } else {
        Session::put("locale", "en");
        App::setLocale(Session::get("locale"));
    }
    dd(Session::get("locale")); // Debug output
    return $next($request);
}
© www.soinside.com 2019 - 2024. All rights reserved.