"使用參數作為前綴,將Laravel的`Auth::routes()`封裝在一個前綴組中"
P粉032900484
P粉032900484 2024-01-10 17:53:38
0
1
454

我正在嘗試在本地化的目的下使用封裝在前綴組中的Laravel Auth::routes()

Route::group(['prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}']], function () {
    Auth::routes();
});

在我的視圖中,我現在在建立路由時提供當前語言,像這樣 route('password.confirm', app()->getLocale())

但是當我嘗試使用“忘記密碼”功能時,會拋出異常。我認為這是因為Laravel在內部創建了一個密碼重置鏈接,使用了一個沒有傳遞當前語言參數的命名路由。

Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: password.reset] 
[URI: {locale}/password/reset/{token}] [Missing parameter: locale].

有沒有可能在某種程度上全域使用Auth::routes()並注入缺少的「locale」參數?或者在不重寫Laravel的身份驗證方法的情況下建議的方法是什麼?

P粉032900484
P粉032900484

全部回覆(1)
P粉697408921

我找到了一個解決方案。感謝這個答案 https://stackoverflow.com/a/49380950/9405862 它激發了我向我的路由組添加一個中間件,該中間件為URL添加了缺少的參數:

Route::group([
    'middleware' => HandleRouteLang::class,
    'prefix' => '{locale}',
    'where' => ['locale' => '[a-zA-Z]{2}']
], function () { 
    Auth::routes();
});

我的中間件現在看起來像這樣:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\UrlGenerator;

class HandleRouteLang
{
    private $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }

    public function handle($request, Closure $next)
    {
        // 通过URL中的locale参数设置当前语言
        if ($request->route("locale")) {
            app()->setlocale($request->route("locale"));
        }

        // 为通过命名路由创建的路由设置默认语言值
        $this->url->defaults([
            'locale' => app()->getLocale(),
        ]);

        return $next($request);
    }
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!