7

I have tried showing an error message in a Controller and it doesn't work, but when I use dd, it works.

My Code:

if ($validation->fails())
{
    /*Doesn't work
    foreach ($validation->fails() as $messages) {
        $messages // Doesn't work
    }
    */
    dd($validation->errors); //This works
}
Community
  • 1
  • 1

3 Answers3

12

I noticed none of the provided examples here actually work! So here you go. This was my found solution after realizing that validator->messages() returns a protected object which isn't retrievable.

if ($validator->fails())
{
    foreach ($validator->messages()->getMessages() as $field_name => $messages)
    {
        var_dump($messages); // messages are retrieved (publicly)
    }

}

I would reference MessageBag, which is what messages() returns. And for additional acknowledgement of the Validator class - reference this.

Community
  • 1
  • 1
tfont
  • 10,891
  • 7
  • 56
  • 52
2

$validation->fails() returns a boolean of whether or not the input passed validation. You can access the validation messages from $validation->messages() or pass them to the view where they will be bound to the $errors variable.

See the validator docs.

Dwight
  • 12,120
  • 6
  • 51
  • 64
0

This is what I have just used in an artisan 5.0 console command, to validate the arguments. This is in the fire() method:

    // Create the validator.
    $validator = Validator::make(
        $this->argument(),
        ['field1' => 'required|other|rules']
    );

    // Validate the arguments.
    if ($validator->fails())
    {
        // Failed validation.

        // Each failed field will have one or more messages.
        foreach($validator->messages()->getMessages() as $field_name => $messages) {
            // Go through each message for this field.
            foreach($messages AS $message) {
                $this->error($field_name . ': ' . $message);
            }
        }

        // Indicate the command has failed.
        return 1;
    }

This is an extension on the answer from @tfont

You may need to change where the message is sent ($this->error()) if this command is not being run as an console command, ie CLI, command-line.

Jason
  • 4,411
  • 7
  • 40
  • 53