首页  >  问答  >  正文

"使用参数作为前缀,将Laravel的`Auth::routes()`封装在一个前缀组中"

我正在尝试在本地化的目的下使用封装在前缀组中的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粉032900484P粉032900484257 天前462

全部回复(1)我来回复

  • P粉697408921

    P粉6974089212024-01-11 12:56:03

    我找到了一个解决方案。感谢这个答案 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);
        }
    }

    回复
    0
  • 取消回复