laravel 如何在laravel错误消息数组中获取错误键

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

how to get an error key in laravel error message array

phparrayslaravellaravel-5.3

提问by Mohamed Athif

I am trying to retrieve a key from an array using Laravel error dump ($errors).

我正在尝试使用 Laravel 错误转储 ( $errors)从数组中检索密钥。

The array looks like this

数组看起来像这样

ViewErrorBag {#169 ▼
  #bags: array:1 [▼
    "default" => MessageBag {#170 ▼
      #messages: array:2 [▼
        "name" => array:1 [▼
          0 => "The name field is required."
        ]
        "role_id" => array:1 [▼
          0 => "The role id field is required."
        ]
      ]
      #format: ":message"
    }
  ]
}

Using @foreachloop to get the error message works fine.

使用@foreach循环获取错误消息工作正常。

@foreach($errors->all() as $error)
     <li>{{$error}}</li>
@endforeach

But I want to get that nameand role_id. Is there anyway to achieve that? Thus far i have tried the below and some other methods with no luck.

但我想得到那个namerole_id。有没有办法做到这一点?到目前为止,我已经尝试了以下方法和其他一些方法,但都没有运气。

@foreach ($errors->all() as $key => $value)
       Key: {{ $key }}
       Value: {{ $value }}
@endforeach

回答by The Alpha

It's because, the $errors->all()returns an array of all the errors for all fields in a single array (numerically indexed).

这是因为,$errors->all()返回一个数组,其中包含单个数组中所有字段的所有错误(数字索引)。

If you want to loop and want to get each key => valuepairs then you may try something like this:

如果你想循环并想得到每一key => value对,那么你可以尝试这样的事情:

@foreach($errors->getMessages() as $key => $message)
    {{$key}} = {{$message}}
@endforeach

But , you may explicitly get an item from the errors, for example:

但是,您可以明确地从错误中获取一个项目,例如:

{{ $errors->first('name') }} // The name field is required.

Maybe it's wise to check before you ask for any error for a field using something like this:

也许明智的做法是在使用以下内容询问字段的任何错误之前进行检查:

@if($errors->has('name'))
    {{ $errors->first('name') }}
@endif

This'll help you to show each error at the top/bottom of the field that the error belongs to.

这将帮助您在错误所属字段的顶部/底部显示每个错误。

回答by lewiscool

Use

@foreach($errors->getMessages() as $key => $error )
   Key: {{ $key }}
   Value: {{ $error[0] }}
@endforeach

if you var_dump the value of $error, you get an array:

如果你 var_dump $error 的值,你会得到一个数组:

array(1) { [0]=> string(13) "Successfully!" }

array(1) { [0]=> string(13) "Successfully!" }

thus you need the key (0 in our case) of that array to access the message

因此您需要该数组的键(在我们的例子中为 0)来访问消息

回答by Cool Dude

to loop through errors

遍历错误

@foreach($errors->getMessages() as $key => $message)
{{$key}} = {{$message[0]}}
@endforeach