Reputation: 150
I'm making a REST API that should validate data entry from the user, to achieve that, I made a Request
class that has the rules
function that it should do the validations.
class StoreUpdateQuestionRequest extends Request {
public function authorize() {
return true;
}
public function rules() {
$method = $this->method();
$rules = [
'question' => 'required|min:10|max:140',
'active' => 'boolean',
];
return $method !== 'GET' || $method !== 'DELETE' ? $rules : [];
}
}
So, in the controller, when I try to run an endpoint which it fires the validations, it does work, it fails when it's has to, but it doesn't show me the errors as I expect, even though I defined the error messages in the messages
function contained in the Request
class, instead of showing me that errors, it redirects me to a location. Which sometimes is the result of a request I made before or it runs the /
route, weird.
public function store(StoreUpdateQuestionRequest $request) {
$question = new Question;
$question->question = $request->question;
$question->active = $request->active;
if($question->save()) {
$result = [
'message' => 'A question has been added!',
'question' => $question,
];
return response()->json($result, 201);
}
}
Any ideas? Thanks in advance!
Upvotes: 0
Views: 4237
Reputation: 150
In order to make this work, you have to add an extra header to your request:
Accept: application/json
That did the trick.
Upvotes: 2
Reputation: 1098
You can use controller based validation as described in documentation https://laravel.com/docs/5.2/validation#manually-creating-validators
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'question' => 'required|min:10|max:140',
'active' => 'boolean',
]);
if ($validator->fails()) {
return response()->json($validator->errors());
}
//other
}
Upvotes: 1