I am looking for the most efficient way to handle both ajax requests in the form of synchronization requests using the usual form. As far as I know, there are two processing methods, for example, a new order request:
Option 1: AJAX checks in the controller (check and save to the left for simplicity).
//Check if we are handling an ajax call. If it is an ajax call: return response //If it 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 for me it seems redundant.
Option 2: allow the router to handle request validation and assign 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 to me more understandable from the point of view of routing, but this is not from the point of view of the workload (interaction with the model, etc.).
Solution (by thinkers)
The thinkers' answers were in place and decided this for me. Here are some more details in the extension of the Controller class:
- Create the controller.php file in the application / libraries.
- Copy the controller extension code with the thinkers' answers.
- Go to application / config / application.php and comment on this line: 'Controller' => 'Laravel \ Routing \ Controller',
source share