如何获取 Laravel 控制器方法的所有可能的错误消息

Lea*_*ner 5 php laravel laravel-5 error-messaging

所以我有一个 Laravel 应用程序,它有很多控制器来处理应用程序的各个方面。

现在每个控制器都有不同的方法。大多数方法都定义了验证规则,例如:

$validationArray = [
    'id'=>'required|integer',
    'status'=>'required|string'
];
$validator = Validator::make($request->all(),$validationArray);
if ($validator->fails()){
    return Response::json(['response'=>implode(', ',$validator->messages()->all())],422);
}
Run Code Online (Sandbox Code Playgroud)

现在以下行:

return Response::json(['response'=>implode(', ',$validator->messages()->all())],422);
Run Code Online (Sandbox Code Playgroud)

实际上返回验证规则的任何错误。

我的问题是:有没有办法以编程方式获取所有可能的错误消息?

当然,一种方法是逐条规则地绕过并手动创建列表,但是有数百种方法分散在各种控制器中。

因此,如果有人能指出我以更简单的方式处理所有错误消息的方向,我将不胜感激。

先感谢您!

更新

所以为了进一步清除,我需要一个所有可能错误的列表,就像上面的代码一样:

['id is required', 'id must be an integer', 'status is required', 'status must be an string']
Run Code Online (Sandbox Code Playgroud)

更新 2

请记住,有数百种方法,而且我不想更改该方法的最终响应,而是希望拥有某种外部脚本,它可以帮助我在不干扰控制器的情况下获取错误消息。

Sty*_*tyx 5

为了做到这一点,您必须扩展Validator类并编写一个方法来迭代所有规则并显式添加错误消息,就好像它们失败一样。

首先,创建一个新文件app\Http\Custom\Validator.php

<?php

namespace App\Http\Custom;

use Illuminate\Contracts\Validation\Rule as RuleContract;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\ValidationRuleParser;
use Illuminate\Validation\Validator as BaseValidator;

class Validator extends BaseValidator {

  /** @var MessageBag */
  protected $errorMessages;

  /** @var array */
  protected $hasExplicitFileErrorMessage;

  protected $explicitFileRules = [
    'File', 'Image', 'Mimes', 'Mimetypes', 'Dimensions',
  ];

  function availableErrors()
  {
    $this->errorMessages = new MessageBag();
    $this->hasExplicitFileErrorMessage = [];

    foreach($this->rules as $attribute => $rules) {
      $attribute = str_replace('\.', '->', $attribute);
      foreach($rules as $rule) {
        [$rule, $parameters] = ValidationRuleParser::parse($rule);

        if($rule == '') {
          continue;
        }
        if(($keys = $this->getExplicitKeys($attribute)) &&
          $this->dependsOnOtherFields($rule)) {
          $parameters = $this->replaceAsterisksInParameters($parameters, $keys);
        }
        // explicitly add "failed to upload" error
        if($this->hasRule($attribute, $this->explicitFileRules) && !in_array($attribute, $this->hasExplicitFileErrorMessage)) {
          $this->addFailureMessage($attribute, 'uploaded', []);
          $this->hasExplicitFileErrorMessage[] = $attribute;
        }

        if($rule instanceof RuleContract) {
          $messages = $rule->message() ? (array)$rule->message() : [get_class($rule)];
          foreach($messages as $message) {
            $this->addFailureMessage($attribute, get_class($rule), [], $message);
          }
        } else {
          $this->addFailureMessage($attribute, $rule, $parameters);
        }
      }
    }

    return $this->errorMessages->all();
  }

  function addFailureMessage($attribute, $rule, $parameters = [], $rawMessage = null)
  {
    $this->errorMessages->add($attribute, $this->makeReplacements(
      $rawMessage ?? $this->getMessage($attribute, $rule), $attribute, $rule, $parameters
    ));
  }

  // we have to override this method since file-type errors depends on data value rather than rule type
  protected function getAttributeType($attribute)
  {
    if($this->hasRule($attribute, $this->explicitFileRules)) {
      return 'file';
    }
    return parent::getAttributeType($attribute);
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,让我们在验证工厂中注册这个类:

<?php

namespace App\Providers;

use App\Http\Custom\Validator; // <-- our custom validator
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {

  public function boot()
  {
    app('validator')->resolver(function ($translator, $data, $rules, $messages) {
      return new Validator($translator, $data, $rules, $messages);
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

就这样。让我们测试一下:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class HomeController extends Controller {

  function index(Request $request)
  {
    $rules = [
      'id'      => 'required|int|between:2,10',
      'status'  => 'required_with:nonexisting|string|email',
      'avatar'  => 'required|file|mimes:png|max:1000',
      'company' => 'required_without:id|unique:companies,id'
    ];

    $validator = Validator::make([], $rules);

    dump($validator->availableErrors());
  }

}
Run Code Online (Sandbox Code Playgroud)
array:13 [?
  0 => "The id field is required."
  1 => "The id must be an integer."
  2 => "The id must be between 2 and 10."
  3 => "The status field is required when nonexisting is present."
  4 => "The status must be a string."
  5 => "The status must be a valid email address."
  6 => "The avatar failed to upload."
  7 => "The avatar field is required."
  8 => "The avatar must be a file."
  9 => "The avatar must be a file of type: png."
  10 => "The avatar may not be greater than 1000 kilobytes."
  11 => "The company field is required when id is not present."
  12 => "The company has already been taken."
]
Run Code Online (Sandbox Code Playgroud)