Search code examples
laravellumen

lumen laravel: How to return the message of the first error?


I need to customize the validation response in Lumen as follow

{
    "result": null,
    "count": 0,
    "statusCode": -1,
    "statusMessage": "...."
}

As you see, Only one status message must be shown, no matter how many errors occurred. To do so, I added the following function in base controller

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    $string = null;

    foreach ($errors as $error)
    {
        $string = $error[0];
        break;
    }

    return [
        "result" => null,
        "count" => 0,
        "statusCode" => -1,
        "statusMessage" => $string
    ];
}

This is the result of dd($errors)

array:2 [
    "user_id" => array:1 [
        0 => "The user id field is required."
    ]
    "asd" => array:1 [
        0 => "The asd field is required."
    ]
]

It works but it seems messy! How can I return the message of the first error?


Solution

  • Take advantage of Collections. If $errors are already a collection (surely an ErrorBag), you can have it as array errors and then flatten them.

    $errors = collect($errors);
    
    $string = $errors->flatten()->first();