Skip to content
Advertisement

Validation errors in AJAX mode

Currently I use this to display validation errors via ajax:

JavaScript

It works fine, does exactly what I need.

The problem is what I have to do to transport the errors from laravel to ajax:

JavaScript

If I want to have the field names as key, I have to iterate $rules, but even if I don’t use field names as key, yet I have to iterate error messages to construct $verrors.

How could I convert $v->messages() to the equivalent of $verrors without the need to iterate? Since Response::json() is expecting an array instead of an object.

Advertisement

Answer

The easiest way is to leverage the MessageBag object of the validator. This can be done like this:

JavaScript

This would give you a JSON response like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement