2

I have a fresh 5.3 installation and want to make api calls with postman. I also tried it with angular2 to make sure it's not a problem with postman.

In my routes/api.php I got a simple route:

Route::post('test', function(\App\Http\Requests\LoginRequest $request) {
    return $request->all();
});

LoginRequest is checking if the fields email and password are there. If so, the output is as excepted. But when it's missing it redirects to /.

Do I have to add some information for form validation for ajax calls? I thought laravel would return a json error object when there is an ajax call.

Update:

I found out that I missed the Accept application/json header in Postman. With it it works finde. But is there a way to say that all api/* calls should be treated as a json call?

3
  • How you get a redirect when you make an AJAX request? Do you get the contents from / as a response? Commented Nov 25, 2016 at 13:04
  • Updated my answer Commented Nov 25, 2016 at 13:07
  • Related: stackoverflow.com/questions/31507849/… Commented Nov 25, 2016 at 17:53

2 Answers 2

1

I created a new parent class for my Requests. It checks if the route belongs to the api group or not. I tried to add a Middleware to the group to add the header, but this trick failed.

class JsonRequest extends FormRequest
{
    public function expectsJson()
    {
        return ($this->route()->getAction()['middleware'] == 'api');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can response to ajax call like this

 return response()->json(array('error' => $validator->getMessageBag()->toArray()), 400);

response status 400 indicates error and you will get in error section

error: function(jqXHR, textStatus, errorThrown){       
  var errResponse = JSON.parse(jqXHR.responseText);
  if (errResponse.error) {
    $.each(errResponse.error, function(index, value)
    {   
       console.log(value);
    });
  }
}

1 Comment

I want to use the FormRequest class so the code inside the controller is as small as possible.

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.