"Use parameters as prefixes to encapsulate Laravel's `Auth::routes()` in a prefix group"
P粉032900484
P粉032900484 2024-01-10 17:53:38
0
1
456

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粉032900484
P粉032900484

reply all(1)
P粉697408921

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);
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!