我正在使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这里我使用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'],
];
}
Run Code Online (Sandbox Code Playgroud)
以及显示自定义消息,
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.',
];
}
Run Code Online (Sandbox Code Playgroud)
它在邮递员上工作正常,但是当移动开发人员点击 API 时,他会收到422 Unprocessable Entity错误,但不会显示错误消息。我想显示错误消息。
我该如何解决这个问题?
moh*_*apr 11
你应该添加
Accept:application/json
Run Code Online (Sandbox Code Playgroud)
调用 api 时添加到您的请求标头
例如:
尝试这样的事情:
$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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5210 次 |
| 最近记录: |