laravel 如何在控制器中显示验证消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17606366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show Validation message in Controller?
提问by Arryangga Aliev Pratamaputra
I have tried showing an error message in a Controller and it doesn't work, but when I use dd
, it works.
我曾尝试在控制器中显示错误消息,但它不起作用,但是当我使用 时dd
,它起作用了。
My Code:
我的代码:
if ($validation->fails())
{
/*Doesn't work
foreach ($validation->fails() as $messages) {
$messages // Doesn't work
}
*/
dd($validation->errors); //This works
}
回答by tfont
I noticed none of the provided examples here actually work! So here you go. This was my found solution after realizing that validator->messages()
returns a protected object which isn't retrievable.
我注意到这里提供的示例都没有实际工作!所以你来了。这是我在意识到validator->messages()
返回一个不可检索的受保护对象后找到的解决方案。
if ($validator->fails())
{
foreach ($validator->messages()->getMessages() as $field_name => $messages)
{
var_dump($messages); // messages are retrieved (publicly)
}
}
I would reference MessageBag, which is what messages()
returns. And for additional acknowledgement of the Validator class - reference this.
我会引用MessageBag,这是messages()
返回的内容。对于 Validator 类的额外确认 - 参考这个。
回答by Dwight
$validation->fails()
returns a boolean of whether or not the input passed validation. You can access the validation messages from $validation->messages()
or pass them to the view where they will be bound to the $errors
variable.
$validation->fails()
返回输入是否通过验证的布尔值。您可以访问验证消息,$validation->messages()
或将它们传递给将绑定到$errors
变量的视图。
See the validator docs.
请参阅验证器文档。
回答by Jason
This is what I have just used in an artisan 5.0 console command, to validate the arguments. This is in the fire()
method:
这是我刚刚在 artisan 5.0 控制台命令中使用的,用于验证参数。这是在fire()
方法中:
// Create the validator.
$validator = Validator::make(
$this->argument(),
['field1' => 'required|other|rules']
);
// Validate the arguments.
if ($validator->fails())
{
// Failed validation.
// Each failed field will have one or more messages.
foreach($validator->messages()->getMessages() as $field_name => $messages) {
// Go through each message for this field.
foreach($messages AS $message) {
$this->error($field_name . ': ' . $message);
}
}
// Indicate the command has failed.
return 1;
}
This is an extension on the answer from @tfont
这是@tfont 答案的扩展
You may need to change where the message is sent ($this->error()
) if this command is not being run as an console command, ie CLI, command-line.
$this->error()
如果此命令不是作为控制台命令(即 CLI、命令行)运行,则您可能需要更改消息的发送位置 ( )。