@simioluwatomi if you know the rules for the external service, I would suggest you add those rules to your validator and avoid making the api call.
Sep 26, 2019
2
Level 8
Validation that calls an external API
So I have a method to validate some inputs. Pretty straightforward but it gets complicated
After validating that the user fills the form properly, I have to call an external API to validate the same input against that service. I'm wondering if someone has done this before and which way to go about this.
Form request or custom validator or both? I just need pointers. Thanks
public function validatexxxxxxxx(Request $request)
{
$request->validate([
'forminput1' => ['required'],
'forminput2' => ['required'],
]);
$clientDetailsRequest = $this->client->get("/api/clients/{$request->input('forminput1')}", ['http_errors' => false]);
$clientDetails = json_decode($clientDetailsRequest->getBody(), true);
if ($clientDetailsRequest->getStatusCode() === 200) {
return redirect()
->route('clients.show', ['key' =>$clientDetails['customKey']])
->with('message', [
'status' => 'info',
'body' => 'Client with forminput1 already exists',
]);
}
$forminput1= (new Client())->get(
config('xxxxx.mobile_base_url')."/validation/xxxxxxxx/{$request->input('forminput1')}",
[
'headers' => [
config('xxxxxx.xxxxxxxx') => config('xxxxxxx.'),
],
]
);
$body = json_decode($forminput1->getBody(), true);
if ($body['status'] === 'fail') {
return back()->with('message', [
'status' => 'danger',
'body' => 'Provide a valid forminput1',
]);
}
if ($body['data']['basic_data']['xxxxxxx'] !== $request->input('forminput2') || $body['data']['basic_data']['xxxxxxxx'] !== $request->input('forminput2')) {
return back()->with('message', [
'status' => 'danger',
'body' => 'Provide forminput2 tied to the forminput1',
]);
}
// redirect to another page with a success response;
}
Please or to participate in this conversation.