Request class has a wantsJson method that returns true when json is wanted. I think it is the case with cURL or at least you can specify it in the request headers. So if you request wants json you can return json errors, otherwise act as normal.
Handling form validation in self consumed API
I'm building a website with a built in API which I'm consuming myself. However, I have come across a problem I can't seem to solve.
I have a Screenshot API which accepts certain post data. When consuming the API myself, I submit a form to a route like so:
Route::post('episode/screenshot', ['as' => 'screenshot.store', function () {
HMVC::post('api/screenshot', Input::all());
return Redirect::back();
}]);
I have a validator in the store method in the API like so:
$data = Input::only(['filename', 'url', 'episode_id', 'timecode']);
try {
$this->screenshotForm->validate($data);
} catch (FormValidationException $e) {
// what do?
}
The question is: If I consume the API inside my own application using the form I want to return to the form with the validation errors. But when I consume the API RESTfully (e.g. cURL or Postman etc.) I want it to return a json representation of the validation errors.
How do I solve this problem?
My rules:
protected $rules = [
'timecode' => 'required|date_format:H:i:s',
'filename' => 'required',
'episode_id' => 'required|integer',
'url' => 'required|url',
];
Well for me that code is overkill, Have you looked at dingo/api? Consider using that, it has internal requests too. And you can catch exceptions globally using Api::error() function which of course is an api function so your json issues will be solved and you dont need to try catch several times in each method.
Please or to participate in this conversation.