I want to separate my validator with my controller, but API always responds with a 200 OK
in Postman.
Request validation:
class PostRequest extends FormRequest { use Types; public function authorize() { return true; } public function rules() { // $auth = $this->request->user(); return [ 'name' => 'required|string|max:255', 'country_id' => 'required|exists:countries,id', 'city' => 'required|max:255', 'phone_no' => 'required|regex:/[0-9]{10,13}/', 'occupation' => 'required|max:255' ]; } }
SenderController:
public function store(PostRequest $request) { $auth = $request->user(); $sender = Sender::create([ 'name' => $request->name, 'country_id' => $request->country_id, 'city' => $request->city, 'phone_no' => $request->phone_no, 'occupation' => $request->occupation ]); return new Resource($sender); }
When I’m sending a request without name
, it will return a response with a status of 200. I want to display $validator->errors()
in my response when I forget to input name. How can I do that?
Route and call:
Route::post('sender', 'V1SenderController@store'); POST: localhost:8000/api/v1/sender
Advertisement
Answer
I solved the problem with adding more code in my PostRequest.php
public $validator = null; protected function failedValidation($validator) { $this->validator = $validator; }
and I show the error message by using controller
if (isset($request->validator) && $request->validator->fails()) { return response()->json([ 'error_code'=> 'VALIDATION_ERROR', 'message' => 'The given data was invalid.', 'errors' => $request->validator->errors() ]); }