6

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

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
Irshad Khan
  • 161
  • 2
  • 15
  • welcome to So ... what response your getting in mobile ? – Kamlesh Paul Dec 29 '20 at 05:01
  • HTTP 422 is already the response ...the question is what is being posted (in particular the content-type). Therefore this question is not only a rough duplicate, but it also lacks relevant debugging information. The server-side code might not be wrongful at all. – Martin Zeitler Dec 29 '20 at 05:02
  • Does this answer your question? [How to Fix '422 Unprocessable Entity' when sending a POST request to Redmine API?](https://stackoverflow.com/questions/56711503/how-to-fix-422-unprocessable-entity-when-sending-a-post-request-to-redmine-api) – Martin Zeitler Dec 29 '20 at 05:02
  • #Kamlesh Request Failed with status code 422 – Irshad Khan Dec 29 '20 at 05:09
  • Just tell that guy to set the proper content-type with his/her post... because I have issues to decide which of the 3 possible close-reasons I should apply. As it is, it is nothing that would be reproducible... and since postman works, the error is on his/her side, not yours (and I'm not trying to shift the blame here). – Martin Zeitler Dec 29 '20 at 05:16
  • I added content type and still getting error – Irshad Khan Dec 29 '20 at 05:18
  • Error: Request failed with status code 422 at createError (createError.js:16) at settle (settle.js:17) at EventTarget.handleLoad (xhr.js:62) at EventTarget.dispatchEvent (event-target-shim.js:818) at EventTarget.setReadyState (XMLHttpRequest.js:592) at EventTarget.__didCompleteResponse (XMLHttpRequest.js:395) at XMLHttpRequest.js:508 at RCTDeviceEventEmitter.emit (EventEmitter.js:189) at MessageQueue.__callFunction (MessageQueue.js:416) at MessageQueue.js:109 – Irshad Khan Dec 29 '20 at 05:18

2 Answers2

10

You should add

Accept:application/json

to your request header when call api

for example:

enter image description here

MAPR
  • 152
  • 1
  • 9
5

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);
Ali Raza
  • 842
  • 7
  • 13