Laravel自定义验证消息无效

时间:2015-12-20 08:29:10

标签: php validation laravel error-handling

我使用L5-repository validation使用存储库模式。这是我的

控制器

<?php

namespace App\Api\V1\Controllers;

use Request;
use Dingo;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Api\V1\Transformers\BankAccountTransformer;
use Prettus\Validator\Exceptions\ValidatorException;
use \Prettus\Validator\Contracts\ValidatorInterface;
use App\Api\V1\Validations\BankAccountValidator;

   public function store()
    {
        $request = Request::all();
        try {
                //Validate request body
                $this->validator->with(  $request )->passesOrFail(ValidatorInterface::RULE_CREATE);

        }  catch (ValidatorException $e) {
                throw new Dingo\Api\Exception\StoreResourceFailedException('Unable to add bank account', $e->getMessageBag()); 
  //  Wiki of the project says to use getMessage(), but it throws error

        }
    }

验证类

<?php

    namespace App\Api\V1\Validations;

    use \Prettus\Validator\Contracts\ValidatorInterface;
    use \Prettus\Validator\LaravelValidator;

    class BankAccountValidator extends LaravelValidator {

        protected $rules = [
            ValidatorInterface::RULE_CREATE => [
            'bank_name' => 'required'
            ],
            ValidatorInterface::RULE_UPDATE => [
            ]
        ];

        protected $messages = [
            'bank_name.required' => 'My custom error'
        ];

    }

但是当我使用 $ e-&gt; getMessage()时,我收到此错误。

  "message": "Call to a member function isEmpty() on string"

如果我使用 $ e-&gt; getMessageBag(),我会收到正确的错误回复。但是我的自定义消息不会显示。显示通用消息。

"errors": {
    "bank_name": [
      "The bank name field is required."
    ]
  }

实际应该是

"errors": {
    "bank_name": [
      "My customer error"
    ]
  }

DD($ E)

ValidatorException {#505
  #messageBag: MessageBag {#507
    #messages: array:1 [
      "bank_name" => array:1 [
        0 => "The bank name field is required."
      ]
    ]
    #format: ":message"
  }
  #message: ""
  #code: 0
  #file: "/home/vagrant/dev-develop/vendor/prettus/laravel-validation/src/Prettus/Validator/AbstractValidator.php"
  #line: 109
  -trace: array:58 [
    0 => array:3 [
      "call" => "Prettus\Validator\AbstractValidator->passesOrFail()"
      "file" => "/home/vagrant/dev-develop/app/Api/V1/Controllers/BankAccountController.php:61"
      "args" => array:1 [
        0 => "create"
      ]
    ]

0 个答案:

没有答案