【问题标题】:Laravel use Request validation with apiLaravel 使用 api 进行请求验证
【发布时间】:2017-01-19 05:53:25
【问题描述】:

我正在尝试像这样在我的 api 中实现验证:

public function store(RideUpdateRequest $request)
    {
        $user = JWTAuth::parseToken()->authenticate();

        $ride = Ride::create([
            'user_id'       => $user->id,
            'time'          => $request->time,
            'date'          => $request->date,
            'type_id'       => $request->type_id,
            'location_id'   => $request->location_id,
            'billabletime'  => $request->billabletime
        ]);

        $ride->save();

        return response()->json(['success' => 'Rit succesvol aangemaakt.'], 200);
    }

RideUpdateRequest:

 public function rules()
    {
        return [
            'time'             =>  'required|integer',
            'date'             =>  'required|date',
            'type_id'          =>  'required|integer',
            'location_id'      =>  'required|integer',
            'billabletime'     =>  'required|integer'
        ];
    }

那么我怎样才能在 json 中返回错误消息(如果请求验证失败)?现在在邮递员中我什么也没收到?

--编辑--

回复:

{
  "billabletime": [
    "The billabletime field is required."
  ]
}

我可以得到这样的东西吗?:

    {
      "error": {
        "The billabletime field is required."
      }
    }

【问题讨论】:

    标签: php laravel validation


    【解决方案1】:

    如果您查看 FormRequest 类,您会看到 response() 方法定义为:

    public function response(array $errors)
    {
        if ($this->expectsJson()) {
            return new JsonResponse($errors, 422);
        }
        ...
    }
    

    因此,您可以设置Accept: aplication/json 请求标头以符合expectsJson 条件,或者通过在您自己的RideUpdateRequest 类中指定response() 方法来强制默认响应行为:

    public function response(array $errors)
    {
        // Always return JSON.
        return response()->json($errors, 422);
    }
    

    【讨论】:

    • 谢谢!现在还有一个问题,我收到它不像一个对象。那可能吗?请参阅我的编辑以了解我的意思。谢谢你
    • 你可以试试这个:return response()->json(['error' => $errors], 400);
    【解决方案2】:

    回复:

    {
      "billabletime": [
        "The billabletime field is required."
      ]
    }
    

    我可以得到这样的东西吗?:

    {
      "error": {
        "The billabletime field is required."
      }
    }
    

    Laravel 使用这种格式是因为 a) 可能有多个字段验证失败,并且 b) 特定字段可能有多个失败。

    例如:

    {
      "email": [
        "The email field is invalid."
      ],
      "password": [
        "The password field must contain a number.",
        "The password field must contain a special character."
      ]
    }
    

    你的"error": { ... } 也是不必要的,因为 Laravel 的验证系统会在响应中发送一个422 Unprocessable Entity 状态码。

    【讨论】:

    • 好吧,我明白了。但在我的 Angular 应用中,使用这种格式非常困难。
    • @Jamie 然后您需要决定将多个错误中的哪一个发回。
    【解决方案3】:

    在 laravel 8 中,您可以通过覆盖 FormRequest 类中的 failedValidation 函数来控制响应:

    use Illuminate\Http\Response;
    
    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        $response = new Response(['error' => $validator->errors()->first()], 422);
        throw new ValidationException($validator, $response);
    }
    

    【讨论】:

    • 我正在检查 Laravel 8 如何处理 api 验证,感谢您的提示
    • 另外一个小技巧是当你发送API请求时,header需要添加accept:application/json,然后它会自动返回json。
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2018-09-13
    • 2023-03-14
    • 2020-06-02
    • 2017-06-02
    • 2017-10-14
    相关资源
    最近更新 更多