Mannu saraswat
Mannu saraswat

Reputation: 1081

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 ?

Upvotes: -2

Views: 5442

Answers (2)

Taha Mohamed
Taha Mohamed

Reputation: 77

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

Upvotes: 2

N69S
N69S

Reputation: 17205

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.

Upvotes: 3

Related Questions