使用Laravel表单请求验证失败时如何返回自定义响应

时间:2019-06-04 06:38:06

标签: laravel validation

如果当验证数据无效时我们在控制器中使用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()]);
}

4 个答案:

答案 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)
    );
}