Laravel Restful控制器和路由ajax /异步请求

时间:2013-04-03 10:24:30

标签: php rest laravel

我正在寻找使用普通表单将ajax请求作为同步请求处理的最有效方法。据我所知,有两种方法可以处理新的订单发布请求:

选项1:AJAX在Controller中检查(为了简单起见,验证并省略了)。

//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', 'ajax.orders@create');
    Route::put('orders/(:any)', 'ajax.orders@update');
    Route::delete('orders/(:any)', 'ajax.orders@destroy');
} else {
    Route::post('orders', 'orders@create');
    Route::put('orders/(:any)', 'orders@update');
    Route::delete('orders/(:any)', 'orders@destroy');
}

第二个选项在路由方面对我来说似乎更干净,但它不是在工作负载方面(处理模型交互等)。

解决方案(由思想家提供)

思想家的回答是现实,并为我解决了。下面是扩展Controller类的更多细节:

  1. 在application / libraries中创建一个controller.php文件。
  2. 从思想家回复中复制Controller扩展代码。
  3. 转到application / config / application.php并评论此行:    'Controller'=> 'Laravel \路由\控制器',

1 个答案:

答案 0 :(得分:5)

我在Laravel论坛中留下的solution涉及扩展Core控制器类,以管理基于REST的系统的ajax和非ajax请求。您只需在控制器中添加一些函数,而不是检入路由并根据请求传输进行切换,前缀为'ajax_'。因此,例如,您的控制器将具有

功能
public function get_orders() { will return results of non-ajax GET request}
public function ajax_get_orders() { will return results of ajax GET request }
public function post_orders()  {will return results of non-ajax POST request }
public function ajax_post_orders() { will return results of ajax POST request }

您可以找到粘贴here

为了扩展Core Controller类,你必须在application / config / application.php中更改别名'Controller'类,然后将控制器类中的$ajaxful属性设置为true(和{{1如果你想要restuful ajax控制器,也可以。)