Hi, There could be multiple validation errors associated with a single field so you may need to have a top level array for each field that needs to be validated, so the correct structure in this case would be:
{
"message": "Validation Failed",
"errors": {
"title": [
{
"code": "required_field",
"message": "The title field is required."
},
{
"code": "max_field_error",
" message": "The title may not be greater than 50 characters."
}
],
"author":[
{
"code": "required_field",
"message": "The author field is required."
}
]
}
}
Yes you're right you will need to extend the validator class and override the addError method. Here is how you can do it in Laravel 5:
// app/Validators/RestValidator.php
<?php namespace App\Validators;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\Validator;
class RestValidator extends Validator {
/**
* Add an error message to the validator's collection of messages.
*
* @param string $attribute
* @param string $rule
* @param array $parameters
* @return void
*/
protected function addError($attribute, $rule, $parameters)
{
$message = $this->getMessage($attribute, $rule);
$message = $this->doReplacements($message, $attribute, $rule, $parameters);
$customMessage = new MessageBag();
$customMessage->merge(['code' => strtolower($rule.'_rule_error')]);
$customMessage->merge(['message' => $message]);
$this->messages->add($attribute, $customMessage);//dd($this->messages);
}
}
Add the binding in the boot method of `App\Providers\AppServiceProvider.php:
use App\Validators\RestValidator;
...
...
public function boot()
{
\Validator::resolver(function($translator, $data, $rules, $messages)
{
return new RestValidator($translator, $data, $rules, $messages);
});
}
And that's it. I have tested it like this:
Route::get('/validation',function(){
$fields = [
'title' => '3ss',
];
$rules = [
'title' => 'required|max:2|alpha'
];
$valid = Validator::make($fields, $rules);
return [
'message' => 'validation_faild',
'errors' => $valid->errors()
];
});
Output:
{
"message":"validation_faild",
"errors":{
"title":[
{
"code":"max_rule_error",
"message":"The title may not be greater than 2 characters."
},
{
"code":"alpha_rule_error",
"message":"The title may only contain letters."
}
]}
}
Hope it helps!