Consuming my own Laravel API

后端 未结 6 1066
傲寒
傲寒 2020-11-28 19:26

I\'m developing a Laravel 4 app that will make the same CRUD operations on my dataset available through a JSON REST API and a Web UI. It seems that to prevent breaking the D

6条回答
  •  臣服心动
    2020-11-28 19:38

    Taylor Otwell suggested using app()->handle() rather than Route::dispatch() to achieve a clean request.

    For Route::dispatch($request) I noticed if the endpoint of your non-GET request (parameters on the HTTP request body) uses a dependency injected \Illuminate\Http\Request or \Illuminate\Foundation\Http\FormRequest extending instance, state of the parameters, cookies, files, etc. are from the original HTTP request. i.e., for your application's controller action method.

    If parameter names and post method type for your app controller and API controller are the same, you won't notice the difference since the original parameter values are passed on. But when you're manually assembling the 3rd parameter of Request::create(), Route::dispatch() will result in it being ignored.

    app()->handle() fixes that context problem in the Laravel request lifecycle.

    Caveat: app()->handle() affects Illuminate\Support\Facades\Request, refreshing it with this new request instance. As a knock-on effect, calls like Request::isXmlHttpRequest() or redirect()->back() invoked after app()->handle() will cause unpredictable behaviour. I'd suggest tracking the context of your original request and instead use redirect()->to(route('...')) so you strictly control flow and state of your app.

    Given all these corner cases, it may be best to just do a manual curl using a Guzzle HTTP client.

提交回复
热议问题