Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

trogne's avatar

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") ?

0 likes
9 replies
Cronix's avatar
Cronix
Best Answer
Level 67

$validator->errors()->first('body')?

1 like
tykus's avatar

The ValidationException instance has an errors() method which is an instance of MessageBag, so this should work:

$e->errors()->first('body');
trogne's avatar

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
            );
        }
trogne's avatar

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...

trogne's avatar

I must do this :

            $errors = '';
            foreach($e->errors() as $key => $value) {
                $errors .= $value[0];
            }
Snapey's avatar

You might be more comfortable with it if you

$errors = collect($e->errors());
LaraStorm's avatar
<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>
fsyauqy's avatar
$exception->validator->errors();
2 likes

Please or to participate in this conversation.