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?
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.
@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.