Let's imagine a company trying to create an account on your Laravel application. How do we verify that this company actually exists, and isn't just making stuff up?
Every legitimate European business has a VAT number — an official tax ID. Dennenboom's VAT number, for example, is BE0770405771. So rather than trust a signup blindly, we can ask whether that number belongs to a real company, and the data isn't just made up. And we don't have to build that check ourselves.
The Solution to Our Problem
A Small But Neat Package
laravel-vatnumber-checker (created by Bert De Swaef) is a package that will resolve this problem for us. In short, it provides a few APIs we can use in order to make verifying VAT numbers much easier.
Usage
The package simply asks for a VAT number, creates a POST request to a free API by the European Commission, and then returns a response in different possible formats:
- a boolean value
Let's say that we just want to check whether a VAT number is valid or not, and don't need anything else from it. In this case we can use the following method:
This makes a request to verify the existence of this VAT number, and returns true if the VAT number is valid and false if it is invalid.
- the full response
What if we want more information about this business? In that case, the following method gives you the full response from that API, in string format:
As stated before, this returns the API response's body in string format, so you'll have to encode it again yourself in order to use its contents.
- only a name or address
If a person types in their VAT number, it's always nice for them to verify whether they typed in the correct VAT number. In this case, we can also simply get either the name of the business, or the address:
If the VAT number is invalid, a value of null will be returned in both cases.
What About Forms?
Let's say you use this in a form. Instead of having to manually verify whether the VAT number exists, you can also simply put this in your validator files:
This example will pass the validation when the provided VAT number is valid, if not, it will return a clean error message.
Wrapping Up
While it's a very simple package, it makes validating VAT numbers a breeze, and at the same time makes it so only real companies can register themselves in your Laravel application (well, at least the VAT numbers aren't made up).
So the next time you're faced with validation of VAT numbers, make sure to make use of this neat package. You'll save yourself some headaches.
Happy coding!