Is there a way to return Form Request erros as a json?
I am making an API to AngularJS, and I am having problems with the error flags
Here is my rules:
class CreateProductRequest extends Request
{
public function rules()
{
return [
'code'=>'required|unique:products',
'style'=>'required|max:12',
'measure'=>'required|max:12',
];
}
This is the response from CreateProductRequest
{
code: [0: "Code is required"],
style:[0: "Style is required"],
measure:[ 0: "Measure is required"]
}
I want the same result as $validator->errors()->all() on the controller, like this:
"messages": [
"Code is required",
"Style is required",
"Measure is required"
]
How can I get this result from Form Request?
Laravel version: master
Form Request errors are already returned as json for AJAX requests. But to achieve the structure you want, you have to override the response function in vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php
Copy the function from there and paste it in Request class in app/Http/Requests/Request.php. Change the following line:
return new JsonResponse($errors, 422);
to this:
$messages = array();
foreach ($errors as $element) {
foreach ($element as $element_error) {
$messages[] = $element_error;
}
}
$response['messages'] = $messages;
$response['status'] = 'error';
return new JsonResponse($response, 200);
Instead of 200, you can return any other status code you are using already, maybe from 4xx series. Add this at the top of this file:
use Illuminate\Http\JsonResponse;
try this
return $validator->errors()->all()->toJson();