Search code examples
laravellumen

Get Laravel Validation Keyed By Failed Rules


I'm trying to do backend validation in Laravel for a VUE SPA. I'm trying to return errors to the frontend keyed by the actual rule that failed, because my frontend needs to perform some other logic based on what exactly went wrong.

For example, I'd like to get this data structure back:

{
"errorMessages": {
    "primary_email": {
        "unique": "Email already exists in SSO."
    },
    "adults": {
        "size": "The adults array must contain 1 item."
    },
    "children": {
        "size": "The children array must contain 2 items."
    }
}

Working with the validator, the only structure I can get back is just an array of error messages grouped by field name, or an array of all messages. I can't figure out a way to get a listing of the rules that failed.

Thanks, Andrew


Solution

  • Validator has method failed(), if you try to 'intersect' it with errors() you should achieve what you want:

    $validator = Validator::make ($request->all(), [/* rules*/]);
    
    if ($validator->fails())
    {
        $errMsgs = [];
    
        foreach ($validator->errors()->toArray() as $field => $msgs)
            foreach (array_keys($validator->failed()[$field]) as $ind => $errorType)
                $errMsgs['errorMessages'][$field][$errorType] = $msgs[$ind];
    
    }
    
    // dd($errMsgs);