使用Trait(处理程序)和表单请求验证表单Laravel的问题

问题描述 投票:1回答:1

早上好,我遇到了麻烦。让我详细一点,我将非常感激你的

我有一个存储资源的控制器 - 一个捕获http_error_codes的特性(404,500)问题是当我尝试在数据库上保存重复的寄存器时验证器没有工作。我正在使用Request进行验证,我希望如果是查询异常,则会显示一条消息“此字段不能重复(例如)”

Mi控制器

    public function store(StoreCategory $request)
{
    $data = request()->all();
    $newCategory = Category::create($data);               
    return $this->respondCreated(new CategoryResource($newCategory)); 
}

我的特点

    public function respondCreated($data)
{
    $response = $data->response();
    return $this->setStatusCode(IlluminateResponse::HTTP_CREATED)->respond(
        $response
    );
}

    public function respond($data, $headers = [])
{
    $response = $data;
    return $response->setStatusCode($this->statusCode);        
}

根据我的特点,我正在验证状态代码,但我的数据库上的所有重复寄存器都显示为404,因为我无法验证

      if ($this->isModelNotFoundException($e)) {
      return $this->modelNotFound();
    } elseif ($this->isHttpException($e) && $e->getStatusCode() == 404 ){
        return $this->modelNotFound();
    } elseif ($this->isHttpException($e) && $e->getStatusCode() >= 500){
        return $this->internalError();
    } else{
        return $this->badRequest();
    }        

我的表格申请

    public function rules()
{
    return [
        'name' => 'required|max:50|unique:categories',
        'parent_id' => 'required'
    ];
}

如果你可以帮助我,我将非常感激。提前谢谢你,原谅我的英语,这不是很好

laravel validation
1个回答
1
投票

问题是FormRequest在控制器方法运行之前导致ValidationException。如果您希望自定义响应,可以在app / Exceptions / Handler处进行。做类似的事情:

public function render($request, Exception $exception)
{
    if ($exception instanceof ValidationException) {
        $errors = $exception->validator->getMessageBag();
        //some handling based on errors
    }
}

解决此问题的另一种方法是在FormRequest方法中定义failedValidation:

protected function failedValidation(Validator $validator)
    {
        throw new CustomValidationException($validator, $this->response(
            $this->formatErrors($validator)
        ));
    }

然后使用render方法(对于Laravel> = 5.5)定义自己的自定义异常类,或者在异常处理程序的render方法中使用instanceof捕获它

如果要在没有异常的情况下解决问题,可以根据验证逻辑move validation to controller创建自定义响应

© www.soinside.com 2019 - 2024. All rights reserved.