如果当验证数据无效时我们在控制器中使用laravel form requests,则表单请求将使用errors
变量进行重定向以返回。
当数据无效时,如何禁用此重定向并返回自定义错误响应?
我将对GET|POST|PUT
请求类型使用表单请求。
我很累Validator
类来解决我的问题,但是我需要使用表单请求。
$validator = \Validator::make($request->all(), [
'type' => "required|in:" . implode(',', $postTypes)
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
答案 0 :(得分:3)
创建自定义FormRequest
类是一种方法。
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
class FormRequest extends \Illuminate\Foundation\Http\FormRequest
{
protected function failedValidation(Validator $validator)
{
if ($this->expectsJson()) {
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json(['data' => $errors], 422)
);
}
parent::failedValidation($validator);
}
}
类位于app/Http/Requests
目录中。经过测试并在Laravel 6.x中工作。
答案 1 :(得分:0)
基类FormRequest
具有方法failedValidation
。尝试在您的FormRequest
后代中覆盖它
use Illuminate\Contracts\Validation\Validator;
class SomeRequest extends FormRequest
{
...
public function failedValidation(Validator $validator)
{
// do your stuff
}
}
答案 2 :(得分:0)
*use this on function*
dont forget to take on top // use App\Http\Requests\SomeRequest;
$validatedData = $request->validated();
\App\Validator::create($validatedData);
*create request php artisan make:request SomeRequest*
ex.
use Illuminate\Contracts\Validation\Validator;
class SomeRequest extends FormRequest
{
public function rules()
{
return [
'health_id' => 'required',
'health' => 'required',
];
}
}
答案 3 :(得分:0)
这是一样的,但写法不同:
protected function failedValidation(Validator $validator)
{
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json([
'message' => "",
'errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
);
}