InfyOmLabs / laravel-generator

API and Admin Panel CRUD Generator for Laravel.
https://www.infyom.com/open-source
MIT License
3.79k stars 812 forks source link

API Validation Request Response #623

Closed pakcybershagufta closed 5 years ago

pakcybershagufta commented 5 years ago

I want little to add success false in api Request(Validation -422 status code) call ?How i can change help please?

mitulgolakiya commented 5 years ago

@pakcybershagufta you can go and change the sendResponse function into AppBaseController.

pakcybershagufta commented 5 years ago

I want change api REQUEST Class response change .Which is with status code 422 .Validation response not whole.

pakcybershagufta commented 5 years ago

use InfyOm\Generator\Request\APIRequest;

class CreateCartAPIRequest extends APIRequest

APIRequest class should i add response method or what i should do

mitulgolakiya commented 5 years ago

Then probably you should read more here. https://laravel.com/docs/5.8/validation#customizing-the-error-messages

Also, maybe in case of APIs, you will need to customize report function in app/Exceptions/Handler.php, handle ValidationException and send the response you want. As this validation has been sent by FormRequest class from failedValidation function.

pakcybershagufta commented 5 years ago

If you want to customize validation response only for selected Request class, you need to add failedValidation() message to this class:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { $response = new JsonResponse(['data' => [], 'meta' => [ 'message' => 'The given data is invalid', 'errors' => $validator->errors() ]], 422);

throw new \Illuminate\Validation\ValidationException($validator, $response);

}

This way you don't need to change anything in Handler and have this custom response only for this single class.

And if you want to change format globally for all responses you should add to app\Exceptions\Handler.php file the following method:

protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'data' => [], 'meta' => [ 'message' => 'The given data is invalid', 'errors' => $exception->errors() ] ], $exception->status); }