Reputation: 13562
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?
Upvotes: 2
Views: 1054
Reputation: 13562
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');
}
}
Upvotes: 1
Reputation: 2736
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);
});
}
}
Upvotes: 0