Laravel5.4でWebAPIを作っています。
FormRequestで入力値のバリデートを行なっているのですが、バリデート失敗時にリダイレクトして欲しくありません。
FormRequestのソースをみてみると、jsonを期待しているかどうかでリダイレクトかjsonでエラーを返すのかを判定しているような箇所を見つけました。
php
1 /** 2 * Get the proper failed validation response for the request. 3 * 4 * @param array $errors 5 * @return \Symfony\Component\HttpFoundation\Response 6 */ 7 public function response(array $errors) 8 { 9 if ($this->expectsJson()) { 10 return new JsonResponse($errors, 422); 11 } 12 13 return $this->redirector->to($this->getRedirectUrl()) 14 ->withInput($this->except($this->dontFlash)) 15 ->withErrors($errors, $this->errorBag); 16 }
テスト用のAPIクライアントに何かヘッダを付けてあげればexpectsJson()
がtrueになり、jsonを返してくれるはずと思い、expectsJson()
が定義されている場所を探しましたが見つけ切れませんでした。しかし、探している途中でRequestクラスにajax()
というメソッドが定義されているのを見つけました。
php
1 /** 2 * Determine if the request is the result of an AJAX call. 3 * 4 * @return bool 5 */ 6 public function ajax() 7 { 8 return $this->isXmlHttpRequest(); 9 }
php
1 /** 2 * Returns true if the request is a XMLHttpRequest. 3 * 4 * It works if your JavaScript library sets an X-Requested-With HTTP header. 5 * It is known to work with common JavaScript frameworks: 6 * 7 * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript 8 * 9 * @return bool true if the request is an XMLHttpRequest, false otherwise 10 */ 11 public function isXmlHttpRequest() 12 { 13 return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); 14 }
よって、FormRequestのresponse()
を以下のようにオーバーライドすると目的の動作が可能だとわかりました。しかし、すごく気持ち悪いです。
php
1 public function response(array $errors) 2 { 3 if ($this->ajax()) { // この行を変更 4 return new JsonResponse($errors, 422); 5 } 6 7 return $this->redirector->to($this->getRedirectUrl()) 8 ->withInput($this->except($this->dontFlash)) 9 ->withErrors($errors, $this->errorBag); 10 }
質問したいことは以下の二つです。
(1)expectsJson()
はどこで定義されているのでしょうか?
(2)FormRequest内でresponse()
をオーバーライドするより美しい方法はありますでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/25 05:36 編集
2017/07/25 05:43
2017/07/25 05:47 編集
2017/07/25 05:46
2017/07/25 05:46
2017/07/25 05:47
2017/07/25 05:47
2017/07/25 05:48
2017/07/25 05:49