Convert Laravel Validation Message Point Syntax to Array

I am using Laravel on the server side. Imagine that our controller receives two fields url[string] and data[array with index head]. We can verify data and customize error messages using

$this->validate($request, [

    'url' => 'required',
    'data.head' => 'required',

], [

    'url.required' => 'The :attribute field is required',
    'data.head.required' => 'The :attribute field is required',
]);

If the check is not completed, Laravel sends a response with json data

{
    "url": ["The url field is required"],
    "data.head": ["The data.head field is required"]
}

How can we convert the response data to send json as below?

{
    "url": ["The url field is required"],
    "data": {
        "head": ["The data.head field is required"]
    }
}
0
source share
3 answers

Laravel has an array_set helper that converts a notation to a point on an array.

I don't know how you send errors via ajax, but you should be able to do something like this:

$errors = [];
foreach ($validator->errors()->all() as $key => $value) {
  array_set($errors, $key, $value);
}

: , , , :

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],
+1

, , laravel validation.php

'custom' => [
        'parent' => [
            'children' => [
                'required' => 'custom message here'
            ]
        ]

parent.children.

. ya.

0

In javascript

Error cycle

error: function (errors) {
    $.each(errors['responseJSON']['errors'], function (index, error) {
        var object = {};
        element = dotToArray(index);
        object[index] = error[0];
        validator.showErrors(object);
    });
}

convert to dot notation to array notation. ie abc.1.xyz in abc [1] [xyz]

function dotToArray(str) {
    var output = '';
    var chucks = str.split('.');
    if(chucks.length > 1){
        for(i = 0; i < chucks.length; i++){
            if(i == 0){
                output = chucks[i];
            }else{
                output += '['+chucks[i]+']';
            }
        }
    }else{
        output = chucks[0];
    }

    return output
}
0
source

Source: https://habr.com/ru/post/1693506/


All Articles