Change response to Laravel validation post
in general the validation message is similar to my json response
"error_details": {
"email": [
"The email field is required."
],
"password": [
"The password field is required."
]
}
but i want to do
"error_details": {
"password": "The password field is required.",
"email": "The email field is required."
}
source to share
You can use the array_flatten()
helper:
array_flatten($validator->getMessageBag()->getMessages());
This will return a one-dimensional array of all validation errors.
More on Laravel Helpers: http://laravel.com/docs/5.0/helpers
source to share
I stumbled upon this same problem. This is how I did it
Created a class CustomMessageBag
that extends Illuminate\Support\MessageBag
and overrides the methodadd
<?php
namespace App\Extend;
use Config;
use Illuminate\Support\MessageBag as BaseMessageBag;
/**
* Extending Validation Class
*
*/
class CustomMessageBag extends BaseMessageBag{
/**
* Add a message to the bag.
*
* @param string $key
* @param string $message
* @return $this
*/
public function add($key, $message)
{
if ($this->isUnique($key, $message)) {
//remove additional array
$this->messages[$key] = $message;
}
return $this;
}
}
Then created customValidator
that uses the classCustomMessageBag
<?php
namespace App\Extend;
use Input;
use Lang;
use Config;
use App\Extend\CustomMessageBag as MessageBag;
/**
* Extending Validation Class
*
*/
class CustomValidator extends \Illuminate\Validation\Validator {
/**
* Determine if the data passes the validation rules.
*
* @return bool
*/
public function passes()
{
$this->messages = new MessageBag;
// We'll spin through each rule, validating the attributes attached to that
// rule. Any error messages will be added to the containers with each of
// the other error messages, returning true if we don't have messages.
foreach ($this->rules as $attribute => $rules) {
foreach ($rules as $rule) {
$this->validate($attribute, $rule);
}
}
// Here we will spin through all of the "after" hooks on this validator and
// fire them off. This gives the callbacks a chance to perform all kinds
// of other validation that needs to get wrapped up in this operation.
foreach ($this->after as $after) {
call_user_func($after);
}
return count($this->messages->all()) === 0;
}
}
Finally, register the class customValidator
in the methodAppServiceProvider's
boot
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Extend\CustomValidator;
use Event;
use Mail;
use Config;
use Lang;
use Log;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
//Register custom validator class
$this->app->validator->resolver(function($translator, $data, $rules, $messages) {
return new CustomValidator($translator, $data, $rules, $messages);
});
}
}
source to share