【问题标题】:Laravel route ignore locale parameterLaravel 路由忽略语言环境参数
【发布时间】:2020-03-29 17:03:05
【问题描述】:

我有一个区域设置中间件,它从请求中获取第一段并将其设置为区域设置:

public function handle($request, Closure $next)
{
    $locale = $request->segment(1);
    session(['locale' => $locale]);
    app()->setLocale($locale);

    return $next($request);
}

路由随后在区域前缀后面定义,如下所示:

Route::prefix('{lang}')->where(['lang' => '[a-zA-Z]{2}'])->middleware('locale')->group(function () {
    Route::get('conversation/{from}/{to}', 'ConversationController@secureChatPage')->name('chat');
....

我现在遇到的问题是,当我在 ConversationController 中调用方法时,我不能再这样做了:

public function secureChatPage($from, $to)
{ ... }

因为$from 参数采用区域设置的值(例如en)。这意味着我必须在方法属性前面加上另一个变量$locale,并在需要路由参数的地方这样做。

有没有干净的方法解决这个问题?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    对不起,没有别的办法了。

    Laravel 为你的路由添加所有前缀值,无论这些前缀是静态文本还是 slug。稍后,当路由器调度现在已解析的路由时,slug 会随之而来,并作为参数提供给您的控制器。

    the implementation:

    /**
     * Prefix the given URI with the last prefix.
     *
     * @param  string  $uri
     * @return string
     */
    protected function prefix($uri)
    {
        return trim(trim($this->getLastGroupPrefix(), '/').'/'.trim($uri, '/'), '/') ?: '/';
    }
    

    我看到了这种简化的吸引力,但如果按照您的要求完成,那么那些需要前缀信息的路由将需要带外访问器。这会引发注入的幽灵,这是应该避免的。

    【讨论】:

      猜你喜欢
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 2022-01-07
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多