【问题标题】:How to send validation messages to API in Laravel?如何在 Laravel 中向 API 发送验证消息?
【发布时间】:2021-04-05 19:21:09
【问题描述】:

我正在使用 Laravel 8 并使用 API。我已经为表单验证创建了请求类,但是当移动开发人员点击 api 验证消息时,没有按要求显示。 这是我的控制器方法

 public function store(InvoiceStoreRequest $request)
{
    try {
        return $this->responseWithSuccess(true,'Invoice Data',
               $this->invoiceInterface->store($request), Response::HTTP_OK);
    }catch (\Exception $exception){
        return $this->responseWithError($exception->getMessage(),Response::HTTP_OK);
    }
}

这里我使用 InvoiceStoreRequest 类来验证表单。 InvoiceStoreRequest 的代码如下

public function rules()
{
    return [
        'id' => ['required', 'string'],
        'invoice_date' => ['required', 'date'],
        'reference_number' => ['required'],
        'vendor_id' => ['required'],
        'invoice_net_total' => ['required','regex:/^\d*(\.\d{1,2})?$/'],
        'invoice_tax_total' => ['required', 'regex:/^\d*(\.\d{1,2})?$/'],
        'invoice_gross_total' => ['required', 'regex:/^\d*(\.\d{1,2})?$/'],
        'item_count' => ['required', 'numeric'],
        'invoice_type' => ['required','regex:(order|refund)'],
        'provider' => ['required'],
        'detail_url' => ['required'],
        'invoice_photo_url' => ['required'],
    ];
}

以及用于显示自定义消息,

public function messages()
{
    return [
        'invoice_type.regex' => 'The invoice type format is invalid. Invoice Type should be [order,refund]',
        'invoice_net_total.regex' => 'Invoice Net must be Decimal or Numeric value.',
        'invoice_tax_total.regex' => 'Invoice Tex must be Decimal or Numeric value.',
        'invoice_gross_total.regex' => 'Invoice Gross must be Decimal or Numeric value.',
    ];
}

它在邮递员上工作正常。但是当移动开发者点击 API 时,他得到了 422 Unprocessable Entity 的错误,但没有显示错误消息。我想显示错误消息。
我该如何解决这个问题。谢谢

【问题讨论】:

  • 欢迎来到所以...您在移动设备上得到什么回应?
  • HTTP 422 已经是响应......问题是发布的内容(特别是内容类型)。因此,这个问题不仅是粗略的重复,而且还缺乏相关的调试信息。服务器端代码可能根本没有错误。
  • #Kamlesh 请求失败,状态码为 422
  • 只是告诉那个人在他/她的帖子中设置正确的内容类型......因为我有问题要决定我应该申请的 3 个可能的密切原因中的哪一个。事实上,没有什么是可重现的......而且由于邮递员工作,错误在他/她的一方,而不是你的一方(我不想在这里推卸责任)。

标签: php laravel api


【解决方案1】:

试试这样的:

 $validator = Validator::make(request()->all(), [
          'name'     => 'required',
          // ... Rules 
        ]);

        if ($validator->fails()) {
            return response()->json([
              'errors' => $validator->errors(),
              'status' => Response::HTTP_BAD_REQUEST,
            ], Response::HTTP_BAD_REQUEST);
        }

        MODEL::create($validator->validated());

        return response()->json([
          'data'   => [],
          'status' => Response::HTTP_CREATED,
        ], Response::HTTP_CREATED);

【讨论】:

    【解决方案2】:

    你应该添加

    Accept:application/json
    

    调用api时到你的请求头

    例如:

    【讨论】:

    • 我被这个问题困扰了一段时间。谢谢兄弟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2023-03-30
    • 2020-04-18
    • 1970-01-01
    • 2017-07-22
    • 2018-03-11
    • 2013-09-03
    相关资源
    最近更新 更多