lara30453's avatar

Wrapping Validation Errors in 'data'

Hi all,

I have a validator in my Lumen project, specifically in my auth controller sign up method. It returns errors like this:

{
    "name": [
        "The name field is required."
    ],
    "email": [
        "The email field is required."
    ],
    "password": [
        "The password field is required."
    ]
}

But I would like them returned like this:

"data": [
    {
    "name": [
            "The name field is required."
        ],
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
]

Anyone know how to do this in Lumen? I know in Laravel you can extend the form requests class, but that is not available in Lumen.

0 likes
3 replies
quickliketurtle's avatar
Level 16

You can create a custom validator to accomplish this. Here is an example:

$app->post('/user', function (Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required',
    ]);

    return response(
        ['data' => $validator->messages()]
    );
});

Use Validator::make and pass the request and rules. Then you can return your response and wrap the messages however you want. In the example above the response is:

{
    "data": {
        "name": [
            "The name field is required."
        ]
    }
}

Note in order to use the Validator facade you need to uncomment $app->withFacades(); in your bootstrap/app.php file.

Please or to participate in this conversation.