如何在Laravel 5中间件中创建新请求


How can I create a new Request in Laravel 5 Middleware

我有以区域设置为前缀的URL,我想保存本地并修改请求而不重定向它,如何在传递请求之前修改它?

因此,对于像site.com/en/someurl 这样的url

class GetLocale implements Middleware {
 public function handle($request, Closure $next)
 {
    $segment = Request::segment(1); // 'en'
    if( is_valid_language($segment) ){
         // remove local from the request url
         // do something to remove the local and continue
         // as if the url was site.com/someurl
         return $next($request);
    }
    return $next($request);
 }
}

GetLocale运行后,网站的其他部分应该完全忽略区域设置,只看到site.com/someurl.

(这样我们就可以同时使用区域设置和路由注释,并且仍然保留原始标题、发布数据等)**

Laravel Request类有一个duplicate()方法,允许您创建一个重复的请求并覆盖它的某些部分

底层Symfony请求检查服务器变量和头,以确定prepareRequestUri()上的请求URL。

似乎在请求中重写REQUEST_URI服务器变量(duplicate()方法中的$server)应该有助于在没有区域设置片段的情况下重写URL。然而,这似乎是一个非常破解的解决方案


参考:https://github.com/laravel/framework/blob/master/src/Illuminate/Http/Request.php#L613