0

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.

Request class

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.

Controller function

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!

2
  • do print_r($request->all());die; what it returns ? Commented Jun 20, 2016 at 6:44
  • @HimanshuRaval, tried to run that line of code in the first statement of the store function, gets redirected to a route that is not implemented. Commented Jun 21, 2016 at 8:26

2 Answers 2

2

In order to make this work, you have to add an extra header to your request:

Accept: application/json

That did the trick.

Sign up to request clarification or add additional context in comments.

Comments

1

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 
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.