get the message in ValidationException
I'm catching a ValidationException.
$e->getMessage()
That's the default message : "The given data was invalid."
It's not the custom one.
In the ValidationException object, I see my custom message there :
#messages: MessageBag {#485
#messages: array:1 [
"body" => array:1 [
0 => "The body contains spam"
]
]
#format: ":message"
}
But how can I grab this custom message ( "The body contains spam") ?
$validator->errors()->first('body')?
The ValidationException instance has an errors() method which is an instance of MessageBag, so this should work:
$e->errors()->first('body');
No, I don't have access to $errors. I'm catching the exception :
} catch (\Exception $e){
return response(
'Sorry, your reply could not be saved at this time. - '.$e->getMessage(), 422
);
}
I see ! I get the errors from the ValidationException like tha : $e->errors()
Thanks! But it's an array like that :
array:1 [
"body" => array:1 [
0 => "The body contains spam"
]
$e->errors()->first('body'); not working...
I must do this :
$errors = '';
foreach($e->errors() as $key => $value) {
$errors .= $value[0];
}
You might be more comfortable with it if you
$errors = collect($e->errors());
<div id="fail"></div>
<script>
.fail(function(response) {
var errors = response.responseJSON;
var errorsHtml = '';
$.each(errors.errors, function( key, value ) {
errorsHtml += '<span class="help is-danger">' + value[0] + '</span>';
});
$('#fail').html(errorsHtml);
});
</script>
$exception->validator->errors();
Please or to participate in this conversation.