Search code examples
phplaravellaravel-validationlaravel-request

How to show only one error message from Laravel request rules


I am using Laravel request to validate in my controller the requested data

controllerstrong text

and here is my request file data

enter image description here

I am facing two challanges

  1. first I am not able to return custom message using static function
  2. I am not able to send single message as we send in controller validation using errors()->first().

By defalut it is returning like that

enter image description here

but I want like below SS

enter image description here Is there I can send first message using request ?


Solution

  • -To custom message

     Laravel Documents customizing-the-error-messages
    

    -To return a single error message

        //In Request
        use Illuminate\Contracts\Validation\Validator;
        use Illuminate\Http\Exceptions\HttpResponseException;
        
        protected function failedValidation(Validator $validator)
        {
            throw new HttpResponseException(response()->json([
                'success' => false,
                'message' =>$validator->errors()->first(),
                'data' => null,
            ], 422));
        }