I am trying to retrieve a key from an array using Laravel error dump ($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 @foreach
loop to get the error message works fine.
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
But I want to get that name
and role_id
. Is there anyway to achieve that? Thus far i have tried the below and some other methods with no luck.
@foreach ($errors->all() as $key => $value)
Key: {{ $key }}
Value: {{ $value }}
@endforeach
It's because, the $errors->all()
returns an array of all the errors for all fields in a single array (numerically indexed).
If you want to loop and want to get each key => value
pairs then you may try something like this:
@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.
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:
array(1) { [0]=> string(13) "Successfully!" }
thus you need the key (0 in our case) of that array to access the message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With