1

I am creating a simple API for uploading files from mobile app.

In my routes/api.php file I have a route defined:

Route::post("/file", 'UploadController@upload');

then in my controller I validate the request:

public function upload(Request $request){

    $this->validate($request, [
            'name' => 'required',
            'file' => 'file',
            'type' => 'required|in:sign,photo',
        ]);

     // do something here....

}

When the request is correct (it passes the validation) everything works fine and Laravel returns JSON response.

But if the request does not pass the validation, i.e. the name field is missing, Laravel returns 302 page and tries to redirect me to login page.

How can I return proper 40X/50X error with JSON message when validation fails, instead of 302 redirect page?

I'm using Laravel 5.3 and Insomnia for testing the API calls.

1 Answer 1

5

The validate method returns a redirect for normal requests, and JSON for an AJAX request.

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. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

So you have several options, here are a couple:

  • You can set the X-Requested-With header so Laravel thinks it is an AJAX request
  • You can create your validator and call fails() on it and handle your response the way you want to:

$validator = Validator::make($input, $rules);
if ($validator->fails()) {
    // Custom Response
}

If you are only making an API, you may want to consider using Lumen instead as it is more finely tuned for that specific purpose. In addition, it's validation defaults to returning a JSON response.

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

1 Comment

Thanks, X-Requested-With did the trick. But still, it's a little bit weird that a request made from Insomnia is not properly recognised as AJAX request.

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.