atomty
atomty

Reputation: 187

laravel api validation custom message

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?

Upvotes: 1

Views: 574

Answers (1)

AH.Pooladvand
AH.Pooladvand

Reputation: 2059

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.'
    ];
}

Upvotes: 2

Related Questions