我正在寻找最有效的方式来处理这两个AJAX请求作为同步请求使用正常的形式。据我所知,有两种方法可以处理例如新的订单发布请求:Laravel Restfull控制器和路由AJAX /同步请求
选项1:AJAX检查控制器(为简单起见,验证并省略掉)。
//Check if we are handling an ajax call. If it is an ajax call: return response
//If it's a sync request redirect back to the overview
if (Request::ajax()) {
return json_encode($order);
} elseif ($order) {
return Redirect::to('orders/overview');
} else {
return Redirect::to('orders/new')->with_input()->with_errors($validation);
}
在上述情况下,我必须在每个控制器中执行此检查。第二种情况解决了这个问题,但它看起来对我来说太过矫枉过正。
选项2:让路由器处理请求检查并根据请求分配控制器。
//Assign a special restful AJAX controller to handle ajax request send by (for example) Backbone. The AJAX controllers always show JSON and the normal controllers always redirect like in the old days.
if (Request::ajax()) {
Route::post('orders', '[email protected]');
Route::put('orders/(:any)', '[email protected]');
Route::delete('orders/(:any)', '[email protected]');
} else {
Route::post('orders', '[email protected]');
Route::put('orders/(:any)', '[email protected]');
Route::delete('orders/(:any)', '[email protected]');
}
第二个选择似乎在路由方面的清洁剂给我,但它不是工作量(处理模型的相互作用等)的条款。
溶液(思想家)
思想家的答案是当场上解决了这个问题对我来说。继承人扩展控制器类的更多细节:
- 在应用程序/库中创建一个controller.php文件。
- 从思考者的答案复制控制器扩展代码。
- 转到应用/配置/ application.php和注释此行: “控制器” =>“Laravel \路由\控制器”,
非常有趣 – BenjaminRH
这是为我做的。我在扩展控制器方面做了一些额外的研究。原来是小菜一碟。 Laravel让我惊叹不已。 –