How to send validation messages to API in Laravel?

Viewed 2574

I am using Laravel 8 and working on API's. I have created Request Classes for Form validation but when mobile developer hit api validation messages not displaying as required. This is my controller method

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

here i am using InvoiceStoreRequest class to validate form. Code for InvoiceStoreRequest is below

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'],
    ];
}

and for displaying custom messages,

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.',
    ];
}

It work fine on postman. But when Mobile developer hit API he get error with 422 Unprocessable Entity but not showing error messages. I want to show error messages.
how can i solve this. Thanks

2 Answers

You should add

Accept:application/json

to your request header when call api

for example:

enter image description here

Try something like this:

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