Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show Validation message in Controller?

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
}
like image 994
Arryangga Aliev Pratamaputra Avatar asked Jul 12 '13 01:07

Arryangga Aliev Pratamaputra


2 Answers

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.

like image 111
tfont Avatar answered Oct 27 '22 09:10

tfont


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

like image 22
Dwight Avatar answered Oct 27 '22 09:10

Dwight