【问题标题】:Laravel validation on Http request对 Http 请求的 Laravel 验证
【发布时间】:2017-05-26 19:47:50
【问题描述】:

这部分Api是我写的:

public function store(Request $request)
{
    $this->validate($request, [
            'citizenship' => 'required',
            'country' => 'required'
    ]);
...

我正在发送一个 Post 请求,但 Postman 没有传递必填字段之一,并且我没有看到任何错误响应,但它只是将我重定向到应用程序的主页。如何获取错误信息?

【问题讨论】:

  • 你能展示你的validate方法和整个store吗?

标签: php laravel-5 postman


【解决方案1】:

试试这个

try{
    $result = YourModel::validate($attributes);
}catch (\Exception $e){
    throw $e;
}

【讨论】:

    【解决方案2】:

    Laravel 非常聪明。如果您从 Postman 将字段 Accept 设置为 application/json。您会注意到您将收到带有 422 HTTP 状态代码的响应以及所有验证错误。另外(来自"Validation" section of the Laravel Documentation

    在 AJAX 请求期间使用 validate 方法时,Laravel 不会生成重定向响应。相反,Laravel 会生成一个包含所有验证错误的 JSON 响应。此 JSON 响应将与 422 HTTP 状态代码一起发送。

    看看负责发回响应的方法,你就会明白为什么了:)

    public function response(array $errors)
    {
        if ($this->expectsJson()) {
            return new JsonResponse($errors, 422);
        }
    
        return $this->redirector->to($this->getRedirectUrl())
            ->withInput($this->except($this->dontFlash))
            ->withErrors($errors, $this->errorBag);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 2017-11-21
      • 2020-01-13
      • 1970-01-01
      • 2017-10-01
      • 2019-12-31
      • 2020-11-06
      • 2020-08-20
      相关资源
      最近更新 更多