设置中间件以接受字符串或 null

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

我正在尝试在我的 Laravel Inerita (Vue.js) 上设置 localization。我知道

https://github.com/mcamara/laravel-localization
,但这不支持 Inertia(至少我在 Vue.js 文件上运行它没有成功)
{{ __("text") }}
在惯性错误中不起作用:
TypeError: _ctx.__ is not a function

无论如何,我使用的是不同的本地化包,称为

laravel-vue-i18n

我在 Vue.js 上成功使用了它,但是在基于 URL 设置区域设置时遇到了问题。如何设置我的路由/中间件以使用可为空的语言环境(默认为 en)?

文件web.php

                                     // Can be nullable locale?
Route::middleware(['setLocale'])->prefix('{locale?}')->group(function () {
  Route::resource('posts', PostController::class);
  Route::resource('comments', CommentController::class);

});

文件 web.phpSetLocaleMiddleware.php*

class SetLocaleMiddleware
{
    public function handle($request, Closure $next, $locale = 'en')
    {
        \Log::info($locale); // Always logs as 'en' even if I add 'ja' in the URL
        \Log::info($request->route('locale')); // Locale or whatever is the text after localhost/ for some reason

        if (!in_array($locale, ['en', 'ja'])) {
            abort(400);
        }

        App::setLocale($locale);

        return $next($request);
    }
}

文件web.phpapp/Kernel.php*

    protected $middlewareAliases = [
        'setLocale' => \App\Http\Middleware\SetLocaleMiddleware::class,
    ];

预期结果:

// Set application language to Japanese
http://localhost/ja
http://localhost/ja/posts
http://localhost/ja/comments

// Set application language to English as default
http://localhost
http://localhost/posts
http://localhost/comments

注意:它不一定是中间件。

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

要达到预期结果并设置中间件以在 Laravel for InertiaJS (Vue) 中接受可为 null 的语言环境,您可以修改

SetLocaleMiddleware.php
,如下所示:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class SetLocaleMiddleware
{
    public function handle($request, Closure $next)
    {
        $locale = $request->route('locale') ?? 'en';

        \Log::info($locale);

        if (!in_array($locale, ['en', 'ja'])) {
            abort(400);
        }

        App::setLocale($locale);

        return $next($request);
    }
}

此修改允许

SetLocaleMiddleware
接受 URL 中可为空的区域设置。如果 URL 中存在区域设置,则将使用该区域设置;否则,默认区域设置将设置为“en”。

此外,您需要更新您的

web.php
路由以确保正确应用中间件:

use App\Http\Controllers\PostController;
use App\Http\Controllers\CommentController;

Route::middleware(['setLocale'])->group(function () {
    Route::prefix('{locale?}')->group(function () {
        Route::resource('posts', PostController::class);
        Route::resource('comments', CommentController::class);
    });
});

通过这些更改,您的路由现在应该正确处理可为空的区域设置,并相应地设置应用程序语言。

© www.soinside.com 2019 - 2024. All rights reserved.