1

I am trying to write a custom message for a validation in laravel. I have checked online and I saw some post where others solve that same issue by adding a protected function. I have also added the function to my code but it is not working. This is my code This is myFormController.php:

public function req(RegistrationRequest $request){ $validated = $request->validated(); return $validated; )}

This is the RegistrationRequest.php:

use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Exceptions\HttpResponseException;

public function authorize() { return true; }

public function rules()
{
    return [
        'email' => 'required|email',
        'firstname' => 'required|string|max:20',
        'lastname' => 'required|string|max:50',
        'password' => 'required|min:8',
    ];
}  protected function failedValidation(Validator $validator) {
throw new HttpResponseException(response()->json($validator->errors(), 422)); }

When that did not work, I used this:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { throw new \Illuminate\Validation\ValidationException(response()->json($validator->errors(), 422)); }

Please what am I doing wrongly?

1 Answer 1

2

If you want custom messages just override messages method you just need to return an array containing key value pairs of field_name => 'message'

/**
 * Get custom messages for validator errors.
 *
 * @return array
 */
public function messages()
{
    return [
      'field_name.required' => 'field_name is requeired',
      'field_name.max' => 'max length should be something.'
    ];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have gotten it, the error code 422 is the one causing the problem, everything worked well immediately I removed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.