0

I am building an API, the desired output when there is an error is as follows:

{
    "success": false,
    "messages" : [
        {
            "field is missing for example",
            ....
        }
    ]
}

I have a custom request called when from the controller as follows:

public function store(CoverageValueRequest $request, CoverageValueManager $manager){
    $manager->create($request);
    return response()->json(['success' => $manager->isSuccessful(), 'message' => $manager->getErrorMessage()]);
}

if the CoverageValueRequest has an error it would through something similar to this:

[
{
    "series.0.values.0.cells": [
        "The series.0.values.0.cells field is required when none of series.0.values.0.wifi are present."
    ],
    "series.0.values.0.wifi": [
        "The series.0.values.0.wifi field is required when none of series.0.values.0.cells are present."
    ]
}
]

How can I modify the error outcome of the custom request to follow the first posted structure.

Thanks in advance.

Coderji
  • 7,655
  • 5
  • 37
  • 51

1 Answers1

2

All you need to do is implementing your own failedValidation method. Default is

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException($this->response(
        $this->formatErrors($validator)
    ));
}

In fact you should rather leave this method unchanged and implement your own version of default:

protected function formatErrors(Validator $validator)
{
   return $validator->getMessageBag()->toArray();
}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291