Postmanを使用するとき、LaravelのバリデーショエラーがJsonじゃなくabortヘルパのレスポンスが返却された
現象
PostmanでLaravelで作ったAPIにPOSTリクエストを送ったときにFormRequestで定義したバリデーションでエラーになったあとJsonで返却されずに、abortヘルパのレスポンスが返却された
対処
Request Headerが問題だった。 request headerに「Accept: application/json」を入れると解消された。
LaravelのHandlerでException吐く時にexpectsJson
でJsonで返却するかどうかチェックしている。その仕組みは以下のようになっている。
<?php class Request { ... // RequestHeaderからAcceptのvalueを取得する public function getAcceptableContentTypes() { if (null !== $this->acceptableContentTypes) { return $this->acceptableContentTypes; } return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()); } ... }
<?php trait InteractsWithContentTypes { ... // Jsonで返却するかどうか確認 public function expectsJson() { return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || $this->wantsJson(); } // getAcceptableContentTypesから取得した値にjsonが含まれていればtrue public function wantsJson() { $acceptable = $this->getAcceptableContentTypes(); return isset($acceptable[0]) && Str::contains($acceptable[0], ['/json', '+json']); } ... }