PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

[FIXED] How to send validation messages to API in Laravel?

 May 17, 2022     api, laravel, php     No comments   

Issue

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


Solution

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


Answered By - Ali Raza
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing