How to get an error key in an array of laravel error messages

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

The array is as follows:

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 a loop @foreachto get an error message is working fine.

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

But I want to get nameand role_id. Anyway, to achieve this? So far I have tried using below and some other methods with no luck.

@foreach ($errors->all() as $key => $value)
       Key: {{ $key }}
       Value: {{ $value }}
@endforeach
+4
source share
3 answers

This is because it $errors->all()returns an array of all errors for all fields in one array (numerical indexing).

key => value, - :

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

, :

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

, , - , - :

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

/ , .

+6

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

var_dump $error, :

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

, (0 )

+3

sort through errors

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

Source: https://habr.com/ru/post/1654939/


All Articles