REST - Laravel将POST与body重定向到其他路由

时间:2017-05-03 07:27:37

标签: php rest api laravel-5.2

我目前正在重写一个包含多个端点的API。但是,出于传统目的,需要有一个端点可用于访问所有其他端点。我们应该重定向到哪个端点是基于自定义action标头发送以及请求。

示例:

输入:标题 - >行动A. 输出:重定向到'/ some / url''ControllerA @ someAction'

输入:标题 - >行动B. 输出:重定向到'/ some / other / url''ControllerB @ someOtherAction'

通常,我可以使用redirect()方法,但后来我丢失了POST方法的主体。我声明的所有端点都是POST方法。

基本上,问题是如何正确地将POST重定向到另一条路线?

另请注意我不能使用:

App::call('App\Http\Controllers\PlanningController@addOrUpdate', ['request' => $request]);

由于我的方法使用自定义Request类来处理验证。我得到一个异常,告诉参数应该是我的自定义类的类型,并给出了Illuminate\Http\Request

1 个答案:

答案 0 :(得分:0)

我实际上找到了问题的答案。我已经创建了一个中间件,它将根据标头中的值重新创建请求。

这里是中间件的句柄功能(仅在Laravel 5.2上测试):

use Request;
use Route;
use Illuminate\Http\Response;

...

public function handle($request, Closure $next, $guard = null)
{
    // Get the header value
    $action = $request->header('action');

    // Find the route by the action name
    $route = Actions::getRouteByName(action); // This returns some route, i.e.: 'api/v1/some/url'

    // Perform the action
    $request = Request::create(route, 'POST', ['body' => $request->getContent()]);
    $response = Route::dispatch($request);

    return new Response($response->getContent(), $response->status(), ['Content-Type' => 'text/xml']); // the last param can be any headers you like
}

请注意,这可能会与您的项目中的其他中间件冲突。我已禁用其他中间件并为此创建了一个特殊的路由组。由于我们手动将呼叫重定向到另一条路由,因此无论如何都要调用该路由上的中间件。但是,您也可以在控制器函数中实现此代码,然后没有冲突的中间件问题!