php 检查是否存在任何错误消息并在 Laravel 中显示所有错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12419814/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:32:04  来源:igfitidea点击:

Check if any error message exists and show all of them in laravel

phpvalidationlaravel

提问by Suman Ghosh

In laravel for showing all error messages at once i use the following code in the view

在 laravel 中一次显示所有错误消息,我在视图中使用以下代码

<?php 
 $something = $errors->all(); 
 if(!empty($something)): 
?>

<div class = "alert alert-error">                      
  @foreach ($errors->all('<p>:message</p>') as $input_error)
    {{ $input_error }}
  @endforeach 
</div> 

<?php endif; ?>

But when I want to use $errors->all()instead of $somethingin the if condition it's showing an error

但是当我想使用$errors->all()而不是$something在 if 条件中时,它显示了一个错误

Can't use method return value in write context

不能在写上下文中使用方法返回值

Although the above code works fine, I think there may be a better ways to check if any error message exists and if it does then display it.

虽然上面的代码工作正常,但我认为可能有更好的方法来检查是否存在任何错误消息,如果存在则显示它。

回答by Cyprian

Yes, because you can't use any method as empty function parameter. From php docs:

是的,因为您不能使用任何方法作为空函数参数。来自 php 文档:

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

empty() 只检查变量,因为其他任何事情都会导致解析错误。换句话说,以下将不起作用:empty(trim($name))。相反,使用trim($name) == false。

What class is $errors? If it's your own class you can implement such method like 'isEmpty()' and then use in if statement:

$errors 是什么类?如果它是你自己的类,你可以实现像 'isEmpty()' 这样的方法,然后在 if 语句中使用:

if ($errors->isEmpty()) { ...

回答by chipit24

In my controller I use the following code to pass validation errors to my view:

在我的控制器中,我使用以下代码将验证错误传递给我的视图:

return Redirect::to('page')
    ->withErrors($validator);

Then, in my view, I can use the following code to check if errors exist:

然后,在我看来,我可以使用以下代码来检查是否存在错误:

@if($errors->any())
<div id="error-box">
    <!-- Display errors here -->
</div>
@endif

You can also use if($errors->all()).

您也可以使用if($errors->all()).

From the Laravel (v4) docs:

来自Laravel (v4) 文档

Note that when validation fails, we pass the Validator instance to the Redirect using the withErrors method. This method will flash the error messages to the session so that they are available on the next request... [A]n $errors variable will always be available in all of your views, on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

请注意,当验证失败时,我们使用 withErrors 方法将 Validator 实例传递给 Redirect。此方法会将错误消息闪烁到会话中,以便它们在下一个请求中可用... [A]n $errors 变量将始终在您的所有视图中可用,在每个请求中,允许您方便地假设 $错误变量总是被定义并且可以安全地使用。