【问题标题】:Laravel 5.8 access error messageBag for array validationLaravel 5.8 访问错误messageBag 进行数组验证
【发布时间】:2019-03-29 11:46:54
【问题描述】:

我验证了一个二维数组,当验证器失败时,validator->errors() 包含:

MessageBag {#1010 ▼
  #messages: array:8 [▼
    "1.0" => array:1 [▼
      0 => "The 1.0 does not match the format d/m/Y."
    ]
    "2.0" => array:1 [▶]
    "1.1" => array:1 [▶]
    "2.1" => array:1 [▶]
    "1.2" => array:1 [▶]
    "2.2" => array:1 [▶]
    "1.4" => array:1 [▶]
    "2.4" => array:1 [▶]
  ]
  #format: ":message"
}

现在我可以像这样访问所有错误:

foreach ($errors->all() as $error) {

}

这会将消息放在$error = "The 1.0 does not match the format d/m/Y.";

如何访问“1.0”键?

【问题讨论】:

  • 请问您的意思是如何获取第一条错误消息?
  • 不,我想访问每个错误的关键,“1.0”、“1.1”等
  • 请检查我的答案

标签: laravel-5.8


【解决方案1】:

找到了。 $key 将包含“1.0”和 $error 消息。

   foreach ($errors->getMessages() as $key => $error) {


   }

【讨论】:

    【解决方案2】:

    在MessageBag 中,有一个方法keys(),您可以使用它获得所有MessageBag 键,有关可用于MessageBag 类的方法的更多信息,请查看MessageBag laravel api doc

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2020-01-05
      • 2019-09-06
      相关资源
      最近更新 更多