All of us are aware that Laravel provides a very convenient way of validating forms using form validation. But did you ever find yourself needing to validate a form field using a third-party API? I just hit this requirement recently in a project.
So basically I was saving an API key for a third-party service and was required to validate whether the API key was valid.
I already had the `FormRequest` class created to validate the request. But it does not allow me to validate data against a third-party API. So I thought of creating a custom validation rule where I could send an API request to the API and validate the response.
Here is what I did:
1. Create the custom validation rule
2. Add custom rule to the ApiTokenRule class.
This class makes a request to our third party API with the token that we want to validate. This logic is written inside the
passes function of our rule class. If we receive the
ok response, it means our token is correct and validation is passed. Otherwise, the validation fails.
3. Add the custom rule to FormRequest
The custom rule we created above, should be added to the validation rules for the form request. If we have the FormRequest class available, add the custom rule to
rules() function as below:
In the above code, the
api_key field will be validated against our custom rule every time the form is saved.