veuge0592's avatar

Form Request to validate in my API Rest

Hi everyone, I'm dealing with this for a long and I really can't find a solution, I'm creating a RESTful API derived from an old project I have. So I have defined the rules of validation in several form requests, and I want to use the same form requests to validate inputs in my API. So for example

public function store(PatientRequest $request){
     Patient::create($request->all());

     return response()->json([
          'message' => 'Saved successfully'
     ], );
 }

The problem here is that I cannot trigger a json response in case the validation fails. Any thoughts?

0 likes
6 replies
ctroms's avatar
ctroms
Best Answer
Level 15

If you are hitting this endpoint with an ajax request Laravel will return your form request error as json for you. If you need to override your form request response you can define a response() method in your Form Request.

Dig into Illuminate\Foundation\Http\FormRequest and look at the response() method to see how it works.

2 likes
veuge0592's avatar

Thanks @ctroms I just overrided my response() method and it works as expected, very appreciated!!!

1 like
ctroms's avatar

@melihovv This solution was to literally create a new method called response() in the Form Request and add write any code to accomplish the task at hand. I'm not exactly sure what you are trying to do. Since this question has already been marked as answered, you may get additional help if you create a new question with the specific issue you are running into, including code examples of what you have tried so far. I am sure people will try to help. Myself included.

baracula94's avatar

@melihovv put this code below method messages() in your Form Request

public function response(array $errors){ return Response::json($errors, 400); }

Please or to participate in this conversation.