0
votes

Laravel 5.2 docs state:

AJAX Requests & Validation

In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Src: https://laravel.com/docs/5.2/validation#quick-ajax-requests-and-validation

However, this doesn't seem correct. A simple CURL call to a route using validation, still returns HTML/a redirect:

curl -X POST -H "Content-Type: application/json" 
-H "Cache-Control: no-cache" 
-d '{}' "http://yours.com/user/register"

The response of the above is HTML, and a redirect. It's not JSON.

Even this page: https://laravel.com/docs/5.2/requests#retrieving-input states:

Retrieving JSON Input Values

When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json.

So what have we missed? What is the solution?

1

1 Answers

1
votes

You also seem to need the following header:

"X-Requested-With: XMLHttpRequest"

Thus:

curl -X POST -H "Content-Type: application/json" 
-H "X-Requested-With: XMLHttpRequest" 
-H "Cache-Control: no-cache"
-d '{}' "http://yours.com/user/register"

And now $this->validate(...) is properly returning a JSON response.