這個問題是因為 FormRequest
中在驗證規則失敗時,會呼叫 failedValidation
方法,該方法的程式碼:
/**
* Handle a failed validation attempt.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
``*
* @throws \Illuminate\Validation\ValidationException
*/
protected function failedValidation(Validator $validator)
{
throw (new ValidationException($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());// 最終在這裡會重定向
}
解決的方法是在自定義的表單驗證類重寫這個方法。
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
.
.
.
protected function failedValidation(Validator $validator)
{
$error= $validator->errors()->all();
throw new HttpResponseException($this->fail(400, $error));
}
protected function fail(int $code, array $errors) : JsonResponse
{
return response()->json(
[
'code' => $code,
'errors' => $errors,
]
);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結