php 如何在Laravel中向API发送验证消息?

kb5ga3dv  于 2022-12-21  发布在  PHP
关注(0)|答案(2)|浏览(122)

我正在使用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.',
    ];
}

它在 Postman 上工作正常。但是当移动的开发人员点击API时,他得到了422不可处理实体的错误,但没有显示错误消息。我想显示错误消息。
我该怎么解决这个问题。谢谢

daupos2t

daupos2t1#

你应该加上

Accept:application/json

到你的请求标头当调用API
例如:

odopli94

odopli942#

试试这样的方法:

$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);

相关问题