Laravel:如何解决和处理路线?

时间:2018-06-02 03:01:19

标签: laravel laravel-5.2

我可以从index.php看到如何让$response对象返回四个Http\Request

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

这几乎是我想要做的,但我需要将路线和POST参数换成新的路线。更具体地说,我有这样的事情:

class AjaxLoaderController extends Controller {

    public static function endpoint(\Illuminate\Http\Request $httpRequest) {

        $kernel = app()->make(Illuminate\Contracts\Http\Kernel::class);

        foreach($httpRequest->request->get('requests',[]) as $subReq) {
            $newReq = $httpRequest->duplicate(null,$subReq['data']);
            // how can I change the URL for $newReq to the resolved path for an arbitrary route name?

            $subRes = $kernel->handle($newReq);

            \Kymark\Dbg::log('$subReq',$subReq);
        }
    }
}

$subReq的样子:

array:1 [
  0 => array:2 [
    "route" => "survey"
    "data" => array:1 [
      "companyId" => 3
    ]
  ]
]

所以我想解决"调查"到一个URL,以便我可以将其填入$newReq然后用{"数据"来热交换$httpRequest中的POST数据,然后通过正常的Laravel管道将其关闭以便它调用新的控制器操作并给我一个新的响应。

1 个答案:

答案 0 :(得分:1)

你在做什么会让你陷入无限循环:(

因为你没有改变路线。

如果我想这样做,我将创建一个新请求,然后将数据添加到其中

你应该在Illuminate之前添加\ ......

$kernel = app()->make(\Illuminate\Contracts\Http\Kernel::class);

... 在你的循环中:

//$newReq = $request->duplicate(null,$subReq);
$newReq = Request::create($subReq['route'], 'POST', $subReq['data']);

$subRes = $kernel->handle($newReq);
$subRes->send();

最后你不应该忘记csrf,因为你发送了一个post请求,你需要除了来自csrf的subReq路由,或者你必须发送带有请求的令牌,

你可以从以下地方除外:

app/Http/Middleware/VerifyCsrfToken.php

或者你可以:

  1. 列表项
  2. 复制请求。检查一下:duplicate method
  3. 获取请求服务器
  4. 根据您的需要更改
  5. 然后使用新参数初始化新请求
  6. 然后用新请求发送路线:D
  7.         $subReq = [
                "route" => "survey",
                "data" => [
                    "companyId" => 3,
                    '_token' => csrf_token(), // if you dont want to except csrf
                ],
            ];
    
    
            $server = $request->server();
    
            $server['REQUEST_METHOD'] = 'POST'; // add it if you are initially sending a GET,
            $server['REQUEST_URI'] = $subReq['route'];
    
            $newRequest = $request->duplicate(null, $subReq['data'], null, null, null, $server);
            $newRequest->initialize([], $subReq['data'], [], $request->cookie(), [], $server, null);
    
            app()->instance('request', $newRequest);
            \Route::dispatch($newRequest);
    
             // or you can still do this
            // $kernel = app()->make(\Illuminate\Contracts\Http\Kernel::class);
            // $subRes = $kernel->handle($newRequest);
            // $subRes->send();
    

    现在,如果您最初发送POST请求,则不需要将post方法类型添加到SERVER,但如果不是,则必须添加它,除了csrf之外,您必须将其添加到属性

    BTW你最后还可以做:

    $kernel = app()->make(\Illuminate\Contracts\Http\Kernel::class);
    $subRes = $kernel->handle($newRequest);
    $subRes->send();