I am looking for the most efficient way to handle both ajax request as sync requests using a normal form. For as far as I know, there are 2 ways to handle for example a new order post request:
Option 1: AJAX checks in the Controller (validation and save left out for sake of simplicity).
//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);
}
In the above case I have to do this check in every controller. The second case solves the problem, but it looks like overkill to me.
Option 2: Letting the router handle the request check and asign controllers based on the request.
//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');
}
The second option seems cleaner to me in terms of routing, but it's not in terms of workload (handling model interaction etc).
Solution (by thinkers)
thinkers answer was spot on and solved it for me. Heres some more details in extending the Controller class:
A solution i left in the Laravel forum involves the extension of the Core controller class to manage both ajax and non ajax requests for a REST based system. Instead of checking in your routes and do switch based on request transport, you simply add some function in your controllers, prefixed by 'ajax_'
. So, for example, your controller will have the functions
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 }
etc.
You can find the paste here
In order to extend the Core Controller class you have to change the alias 'Controller' class in application/config/application.php, then set the $ajaxful
property in your controller class to true (and $restful
also if you want restuful ajax controllers).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With