Capture error from laravel controller with Axios
If you wrap the validate()
method call in a try/catch
block, then you can catch the ValidationException
thrown when the request is invalid. This will allow you to return your own response.
I've shown you an example of this below, and included the validation errors too, should you wish to output these on the front-end.
<?phpuse Illuminate\Validation\ValidationException;public function myProfile(Request $request){ try { $this->validate($request, [ 'firstname' => 'required|min:3|max:15', 'lastname' => 'min:2|max:15', 'gender' => 'numeric', 'description' => 'max:200', ]); return response()->json([ 'status' => 'success', 'msg' => 'Okay', ], 201); } catch (ValidationException $exception) { return response()->json([ 'status' => 'error', 'msg' => 'Error', 'errors' => $exception->errors(), ], 422); }}