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', 'V1\SenderController@store');
POST: localhost:8000/api/v1/sender
You can set any key / pair values in the json, “$validator->errors()” send the error with attribute name in the response. Step 6 : Add “LoginRequest. php” file in the API's controller file. Step 7 : Add “LoginRequest”as a parameter in the controller which you will call from API.
The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.
Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.
You should make sure you're sending the request with the Accept: application/json
header.
Without that - Laravel won't detect that it's an API request, and won't generate the 422 response with errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With