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?
Answer
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.'
];
}
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms