search

Home  >  Q&A  >  body text

"Use parameters as prefixes to encapsulate Laravel's `Auth::routes()` in a prefix group"

I'm trying to use Laravel wrapped in a prefix group for localization purposes Auth::routes():

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

In my views, I now provide the current language when creating routes, like this route('password.confirm', app()->getLocale())

But when I try to use the "Forgot Password" feature, an exception is thrown. I think this is because Laravel creates a password reset link internally, using a named route without passing the current language parameter.

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

Is it possible to use Auth::routes() somehow globally and inject the missing "locale" parameter? Or what is the recommended approach without overriding Laravel's authentication method?

P粉032900484P粉032900484351 days ago567

reply all(1)I'll reply

  • P粉697408921

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

    I found a solution. Thanks for this answer https://stackoverflow.com/a/49380950/9405862 It inspired me to add a middleware to my routing group that adds the missing parameters to the URL:

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

    My middleware now looks like this:

    <?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);
        }
    }

    reply
    0
  • Cancelreply