Home > Mobile >  How to show only one error message from Laravel request rules
How to show only one error message from Laravel request rules

Time:02-23

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 ?

CodePudding user response:

If you are using laravel 8 or 9 you can do that using the attribute $stopOnFirstFailure of your FormRequest Class

class UpdateRequest extends FormRequest
{
    /**
     * Indicates whether validation should stop after the first rule failure.
     *
     * @var bool
     */
    protected $stopOnFirstFailure = false;

    //...
}

as for the response rendering, you need to add a custom render/format in your exception handler (App/Exceptions/Handler.php) to catch the validation exception thrown and return the json format you need.

CodePudding user response:

-For custom message

 Laravel Documents customizing-the-error-messages

-For return 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));
    }
  • Related