2013-04-03 56 views
4

我正在寻找最有效的方式来处理这两个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]'); 
} 

第二个选择似乎在路由方面的清洁剂给我,但它不是工作量(处理模型的相互作用等)的条款。

溶液(思想家)

思想家的答案是当场上解决了这个问题对我来说。继承人扩展控制器类的更多细节:

  1. 在应用程序/库中创建一个controller.php文件。
  2. 从思考者的答案复制控制器扩展代码。
  3. 转到应用/配置/ application.php和注释此行: “控制器” =>“Laravel \路由\控制器”,

回答

6

solution了遗留在Laravel论坛涉及的扩展核心控制器类来管理基于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

为了延长你必须改变别名“控制器核心控制器类'application/config/application.php中的类,然后将控制器类中的$ajaxful属性设置为true(并且如果需要restuful ajax控制器,则还需要$restful)。

+0

非常有趣 – BenjaminRH

+0

这是为我做的。我在扩展控制器方面做了一些额外的研究。原来是小菜一碟。 Laravel让我惊叹不已。 –