我正在使用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无法处理的实体的错误,但未显示错误消息。我想显示错误消息。
我该如何解决。谢谢
尝试这样的事情:
$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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句