通常のフォームを使用して、両方の ajax リクエストを同期リクエストとして処理する最も効率的な方法を探しています。私の知る限り、たとえば新しいオーダー ポスト リクエストを処理するには 2 つの方法があります。
オプション 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 番目のケースで問題は解決しますが、やり過ぎのように思えます。
オプション 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');
}
2 番目のオプションは、ルーティングの点ではすっきりしているように見えますが、ワークロード (モデルの相互作用の処理など) の点ではそうではありません。
解決策(思想家による)
思想家の答えは的を射ていて、私のためにそれを解決しました。Controller クラスの拡張について、さらに詳しく説明します。
- application/libraries に controller.php ファイルを作成します。
- 思想家の回答からコントローラー拡張コードをコピーします。
- application/config/application.php に移動して、次の行にコメントを付けます: 'Controller' => 'Laravel\Routing\Controller',