我确实偶然发现了同样的问题。这是我的做法
创建了一个CustomMessageBag
扩展Illuminate\Support\MessageBag
并覆盖该add
方法的类
<?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;
}
}
然后创建了一个customValidator
使用CustomMessageBag
该类的
<?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;
}
}
最后在方法中注册CustomValidator
类AppServiceProvider'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);
});
}
}