PHPackages                             viddyoze-engineering/vat-calculator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. viddyoze-engineering/vat-calculator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

viddyoze-engineering/vat-calculator
===================================

EU VAT calculation, the way it should be.

2.4.3(5y ago)06MITPHPPHP &gt;=7.1

Since Sep 1Pushed 5y agoCompare

[ Source](https://github.com/viddyoze-engineering/vat-calculator)[ Packagist](https://packagist.org/packages/viddyoze-engineering/vat-calculator)[ RSS](/packages/viddyoze-engineering-vat-calculator/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (6)Versions (34)Used By (0)

VatCalculator
=============

[](#vatcalculator)

[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/a5b918562b1c1a78411f45552d84d1e1a82bc326341e0dab9b860b6c904eb452/68747470733a2f2f7472617669732d63692e6f72672f6d706f63696f742f7661742d63616c63756c61746f722e737667)](https://travis-ci.org/mpociot/vat-calculator)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/409d4e599fbc3af78d2d1d41a680a0c92a33aac172d4510f662e027197f7780d/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d706f63696f742f7661742d63616c63756c61746f722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/mpociot/vat-calculator/?branch=master)[![codecov.io](https://camo.githubusercontent.com/8155e26573ad6f42ffc306ef970bc70ad72404057fb8230c826074384b0c095e/68747470733a2f2f636f6465636f762e696f2f6769746875622f6d706f63696f742f7661742d63616c63756c61746f722f636f7665726167652e7376673f6272616e63683d6d6173746572)](https://codecov.io/github/mpociot/vat-calculator?branch=master)[![StyleCI](https://camo.githubusercontent.com/1ca88945d96e2fdf66bcd9e36f9903655ecf4827b5559b4168c56a554bec2990/68747470733a2f2f7374796c6563692e696f2f7265706f732f34313730333632342f736869656c64)](https://styleci.io/repos/41703624)[![SensioLabsInsight](https://camo.githubusercontent.com/aa629075c4830046450f5a22e2bd859ea81ad371b76d7b0233fb769fbfb711ff/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f61646563623938612d383438342d343863622d626531332d3830336465636334373562632f6d696e692e706e67)](https://insight.sensiolabs.com/projects/adecb98a-8484-48cb-be13-803decc475bc)

Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be. Can be used with **Laravel 5 / Cashier** — or **standalone**.

```
// Easy to use!
$countryCode = VatCalculator::getIPBasedCountry();
VatCalculator::calculate( 24.00, $countryCode );
VatCalculator::calculate( 24.00, $countryCode, $postalCode );
VatCalculator::calculate( 71.00, 'DE', '41352', $isCompany = true );
VatCalculator::getTaxRateForLocation( 'NL' );
// Check validity of a VAT number
VatCalculator::isValidVATNumber('NL123456789B01');
```

Contents
--------

[](#contents)

- [Installation](#installation)
    - [Standalone](#installation-standalone)
- [Usage](#usage)
    - [Calculate the gross price](#calculate-the-gross-price)
    - [Receive more information](#receive-more-information)
    - [Validate EU VAT numbers](#validate-eu-vat-numbers)
        - [Laravel Validator extension](#laravel-validator-extension)
    - [Get EU VAT number details](#vat-number-details)
    - [Cashier integration](#cashier-integration)
    - [Get the IP based country of your user](#get-ip-based-country)
    - [Frontend integration - vat\_calculator.js](#frontend-integration)
        - [Integrating it in your payment form](#payment-form-integration)
        - [Extra fields](#extra-fields)
        - [Form attributes](#form-attributes)
        - [Form fields](#form-fields)
        - [Advanced usage](#advanced-usage)
        - [Preconfigured routes](#preconfigured-routes)
- [Configuration (optional)](#configuration)
- [Changelog](#changelog)
- [License](#license)

Installation
------------

[](#installation)

In order to install the VAT Calculator, just run

```
$ composer require mpociot/vat-calculator
```

### Standalone

[](#standalone)

You can also use this package without Laravel. Simply create a new instance of the VAT calculator and use it. All documentation examples use the Laravel 5 facade code, so make sure not to call the methods as if they were static methods.

Example:

```
use Mpociot\VatCalculator\VatCalculator;

$vatCalculator = new VatCalculator();
$vatCalculator->setBusinessCountryCode('DE');
$countryCode = $vatCalculator->getIPBasedCountry();
$grossPrice = $vatCalculator->calculate( 49.99, 'LU' );
```

Usage
-----

[](#usage)

### Calculate the gross price

[](#calculate-the-gross-price)

To calculate the gross price use the `calculate` method with a net price and a country code as paremeters.

```
$grossPrice = VatCalculator::calculate( 24.00, 'DE' );
```

The third parameter is the postal code of the customer.

As a fourth parameter, you can pass in a boolean indicating whether the customer is a company or a private person. If the customer is a company, which you should check by [validating the VAT number](#validate-eu-vat-numbers), the net price gets returned.

```
$grossPrice = VatCalculator::calculate( 24.00, 'DE', '12345', $isCompany = true );
```

### Receive more information

[](#receive-more-information)

After calculating the gross price you can extract more information from the VatCalculator.

```
$grossPrice = VatCalculator::calculate( 24.00, 'DE' ); // 28.56
$taxRate    = VatCalculator::getTaxRate(); // 0.19
$netPrice   = VatCalculator::getNetPrice(); // 24.00
$taxValue   = VatCalculator::getTaxValue(); // 4.56
```

### Validate EU VAT numbers

[](#validate-eu-vat-numbers)

Prior to validating your customers VAT numbers, you can use the `shouldCollectVAT` method to check if the country code requires you to collect VAT in the first place.

```
if (VatCalculator::shouldCollectVAT('DE')) {

}
```

To validate your customers VAT numbers, you can use the `isValidVATNumber` method. The VAT number should be in a format specified by the [VIES](http://ec.europa.eu/taxation_customs/vies/faqvies.do#item_11). The given VAT numbers will be truncated and non relevant characters / whitespace will automatically be removed.

This service relies on a third party SOAP API provided by the EU. If, for whatever reason, this API is unavailable a `VATCheckUnavailableException` will be thrown.

```
try {
	$validVAT = VatCalculator::isValidVATNumber('NL 123456789 B01');
} catch( VATCheckUnavailableException $e ){
	// Please handle me
}
```

### Get EU VAT number details

[](#get-eu-vat-number-details)

To get the details of a VAT number, you can use the `getVATDetails` method. The VAT number should be in a format specified by the [VIES](http://ec.europa.eu/taxation_customs/vies/faqvies.do#item_11). The given VAT numbers will be truncated and non relevant characters / whitespace will automatically be removed.

This service relies on a third party SOAP API provided by the EU. If, for whatever reason, this API is unavailable a `VATCheckUnavailableException` will be thrown.

```
try {
	$vat_details = VatCalculator::getVATDetails('NL 123456789 B01');
	print_r($vat_details);
	/* Outputs
	stdClass Object
	(
		[countryCode] => NL
		[vatNumber] => 123456789B01
		[requestDate] => 2017-04-06+02:00
		[valid] => false
		[name] => Name of the company
		[address] => Address of the company
	)
	*/
} catch( VATCheckUnavailableException $e ){
	// Please handle me
}
```

### Laravel Validator Extension

[](#laravel-validator-extension)

If you want to include the VAT number validation directly in your existing Form Requests / Validations, use the `vat_number` validtion rule.

Example:

```
$rules = array(
    'first_name'  => 'required',
    'last_name'   => 'required',
    'company_vat' => 'vat_number'
);

$validator = Validator::make(Input::all(), $rules);
```

**Important:** The validator extension returns `false` when the VAT ID Check SOAP API is unavailable.

### Cashier integration

[](#cashier-integration)

If you want to use this package in combination with [Laravel Cashier](https://github.com/laravel/cashier/) you can let your billable model use the `BillableWithinTheEU` trait. Because this trait overrides the `getTaxPercent` method of the `Billable` trait, we have to explicitly tell our model to do so.

```
use Laravel\Cashier\Billable;
use Mpociot\VatCalculator\Traits\BillableWithinTheEU;
use Laravel\Cashier\Contracts\Billable as BillableContract;

class User extends Model implements BillableContract
{
    use Billable, BillableWithinTheEU {
        BillableWithinTheEU::taxPercentage insteadof Billable;
    }

    protected $dates = ['trial_ends_at', 'subscription_ends_at'];
}
```

By using the `BillableWithinTheEU` trait, your billable model has new methods to set the tax rate for the billable model.

Set everything in one command:

- `setTaxForCountry($countryCode, $company = false)`

Or use the more readable, chainable approach:

- `useTaxFrom($countryCode)` — Use the given countries tax rate
- `asIndividual()` — The billable model is not a company (default)
- `asBusiness()` — The billable model is a valid company

So in order to set the correct tax percentage prior to subscribing your customer, consider the following workflow:

```
$user = User::find(1);

// For individuals use:
$user->useTaxFrom('NL');

// For business customers with a valid VAT ID, use:
$user->useTaxFrom('NL')->asBusiness();

$user->subscription('monthly')->create($creditCardToken);
```

Get the IP based Country of your user(s)
----------------------------------------

[](#get-the-ip-based-country-of-your-users)

Right now you'll need to show your users a way to select their country - probably a drop down - to use this country for the VAT calculation.

This package has a small helper function, that tries to lookup the Country of the user, based on the IP they have.

```
$countryCode = VatCalculator::getIPBasedCountry();
```

The `$countryCode` will either be `false`, if the service is unavailable, or the country couldn't be looked up. Otherwise the variable contains the two-letter country code, which can be used to prefill the user selection.

Frontend integration — vat\_calculator.js
-----------------------------------------

[](#frontend-integration--vat_calculatorjs)

Phew - so you know how to use this class, built your fancy payment form and now...? Well - you want to display the correct prices to your users and want it to update dynamically. So go ahead, add some routes, write some Javascript and in no time you'll be up and running, right?

Or you use the **built in routes** and **vat\_calculator.js** library.

The VAT Calculator JS library will automatically:

- Calculate taxes whenever the selected country value changes
- Automatically validate VAT-IDs / VAT numbers and use it for the calculation
- Prefill the user's country with the IP based country

The Javascript library has no dependencies on third party frameworks.

In order to use the Javascript helper you need to publish the package files first. Go ahead and type:

```
$ php artisan vendor:publish --provider="Mpociot\VatCalculator\VatCalculatorServiceProvider"
```

Now you have a file called `vat_calculator.js` in your `public/js` folder.

### Integrating it in your payment form

[](#integrating-it-in-your-payment-form)

Add the published javascript file to your payment form.

```

  ...

```

By default, the VAT Calculator JS script is looking for a form with the ID `payment-form`. This form needs a `data-amount` attribute specifying the amount to use for the tax calculation in **cents** (just like Stripe uses it).

So your form should look like this, when you would calculate the taxes for 24.99 €

```

```

Next up, you need a dropdown to let your users select their billing country. This select field needs the `data-vat="country"` attribute, so that the VAT Calculator JS knows, where to look for country codes.

Since there are also quite a few VAT rate exceptions for specific regions or cities, it is highly recommended to add an input field to collect postal codes. This field needs a `data-vat="postal-code"` attribute.

And last but not least, to automatically validate VAT Numbers / VAT IDs you can have an input field with the `data-vat="vat_number"` attribute specified.

So your form will look like this:

```

                Country

                    United States
                    United Kingdom
                    Germany
                    France
                    Italy
                    Spain
                    Canada
                    Australia

                Postal Code

                VAT Number

```

### Extra fields

[](#extra-fields)

To display the live tax calculation, you can use the classes `vat-subtotal`, `vat-taxrate`, `vat-taxes` and `vat-total` on any DOM element and VAT Calculator JS will automatically set the inner HTML content for you.

Example:

```
Subtotal: €
Tax rate: %
Taxes: €
Total: €
```

### Form attributes

[](#form-attributes)

AttributeDescriptionRequired`data-amount`Use this attribute on the `form` you want to use for live calculation. It's the price in **cent** used for the calculation.Yes

### Form fields

[](#form-fields)

In order to calculate the right taxes, you need to add some extra inputs to your payment form. All these fields need to have a `data-vat` attribute. You need to include at least the `country`.

AttributeDescriptionRequired`country`Customer’s country (2-letter ISO code).Yes`postal-code`Customer's postal codeNo **Highly recommended**`vat-number`Billing VAT numberNo

### Advanced usage

[](#advanced-usage)

#### Use a different form selector

[](#use-a-different-form-selector)

Use `VATCalculator.init('#my-selector')` to initialize the live calculation on a different form.

#### Use a custom formatter function to modify calculation result HTML

[](#use-a-custom-formatter-function-to-modify-calculation-result-html)

Use `VATCalculator.setCurrencyFormatter` to use a different method to format the calculated values for the HTML output. This function will receive the calculation result as a parameter.

Example:

```
VATCalculator.setCurrencyFormatter(function(value){
    return value.toFixed(2) + ' €';
});
```

#### Trigger calculation manually

[](#trigger-calculation-manually)

Call `VATCalculator.calculate()` to trigger the calculation manually. For example when you change the `data-amount` attribute on your form.

### Preconfigured routes

[](#preconfigured-routes)

In order for VAT Calculator JS to work properly, these routes will be added to your application. If you don't want to use the Javascript library, you can of course disable the routes in the [configuration](#configuration) file.

MethodRouteUsage`GET``vatcalculator/tax-rate-for-location/{country}/{postal-code}`Returns the VAT / tax rate for the given country (2-letter ISO code).`GET``vatcalculator/country-code`Returns the 2-letter ISO code based from the IP address.`GET``vatcalculator/validate-vat-id/{vat_id}`Validates the given VAT ID`GET``vatcalculator/calculate`Calculates the gross price based on the parameters: `netPrice`, `country` and `vat_number`

Configuration
-------------

[](#configuration)

By default, the VAT Calculator has all EU VAT rules predefined, so that it can easily be updated, if it changes for a specific country.

If you need to define other VAT rates, you can do so by publishing the configuration and add more rules.

The configuration file also determines wether you want to use the VAT Calculator JS routes or not.

**Important:** Be sure to set your business country code in the configuration file, to get correct VAT calculation when selling to business customers in your own country.

To publish the configuration files, run the `vendor:publish` command

```
$ php artisan vendor:publish --provider="Mpociot\VatCalculator\VatCalculatorServiceProvider"
```

This will create a `vat_calculator.php` in your config directory.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information.

License
-------

[](#license)

This library is licensed under the MIT license. Please see [License file](LICENSE.md) for more information.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 76.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~59 days

Recently: every ~204 days

Total

32

Last Release

2070d ago

Major Versions

1.7.1 → 2.0.02016-06-28

PHP version history (2 changes)1.0.0PHP &gt;=5.5.9

2.4.3PHP &gt;=7.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/fc91f8299aab3ba0a4339243f4b93aa33f52edd3571424e0903b352f5de6a421?d=identicon)[viddyoze](/maintainers/viddyoze)

---

Top Contributors

[![mpociot](https://avatars.githubusercontent.com/u/804684?v=4)](https://github.com/mpociot "mpociot (105 commits)")[![galexth](https://avatars.githubusercontent.com/u/10194439?v=4)](https://github.com/galexth "galexth (3 commits)")[![michellaurent](https://avatars.githubusercontent.com/u/1630290?v=4)](https://github.com/michellaurent "michellaurent (3 commits)")[![iruoy](https://avatars.githubusercontent.com/u/5859352?v=4)](https://github.com/iruoy "iruoy (2 commits)")[![netpok](https://avatars.githubusercontent.com/u/6945600?v=4)](https://github.com/netpok "netpok (2 commits)")[![orottier](https://avatars.githubusercontent.com/u/5442615?v=4)](https://github.com/orottier "orottier (2 commits)")[![webcraft](https://avatars.githubusercontent.com/u/56675?v=4)](https://github.com/webcraft "webcraft (2 commits)")[![mrk-j](https://avatars.githubusercontent.com/u/1250622?v=4)](https://github.com/mrk-j "mrk-j (2 commits)")[![lanort](https://avatars.githubusercontent.com/u/57423?v=4)](https://github.com/lanort "lanort (2 commits)")[![pascalbaljet](https://avatars.githubusercontent.com/u/8403149?v=4)](https://github.com/pascalbaljet "pascalbaljet (1 commits)")[![rossbearman](https://avatars.githubusercontent.com/u/212036?v=4)](https://github.com/rossbearman "rossbearman (1 commits)")[![Shad9w](https://avatars.githubusercontent.com/u/1039563?v=4)](https://github.com/Shad9w "Shad9w (1 commits)")[![spaze](https://avatars.githubusercontent.com/u/1966648?v=4)](https://github.com/spaze "spaze (1 commits)")[![webdevvie](https://avatars.githubusercontent.com/u/6097722?v=4)](https://github.com/webdevvie "webdevvie (1 commits)")[![4rno](https://avatars.githubusercontent.com/u/11329833?v=4)](https://github.com/4rno "4rno (1 commits)")[![willselby](https://avatars.githubusercontent.com/u/11734472?v=4)](https://github.com/willselby "willselby (1 commits)")[![driesvints](https://avatars.githubusercontent.com/u/594614?v=4)](https://github.com/driesvints "driesvints (1 commits)")[![Ettemlevest](https://avatars.githubusercontent.com/u/1035942?v=4)](https://github.com/Ettemlevest "Ettemlevest (1 commits)")[![hanspagel](https://avatars.githubusercontent.com/u/1577992?v=4)](https://github.com/hanspagel "hanspagel (1 commits)")[![kduma](https://avatars.githubusercontent.com/u/1062582?v=4)](https://github.com/kduma "kduma (1 commits)")

---

Tags

vattaxtax calculationcashierEU Mossvat calculationVAT ID

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/viddyoze-engineering-vat-calculator/health.svg)

```
[![Health](https://phpackages.com/badges/viddyoze-engineering-vat-calculator/health.svg)](https://phpackages.com/packages/viddyoze-engineering-vat-calculator)
```

###  Alternatives

[mpociot/vat-calculator

EU VAT calculation, the way it should be.

1.3k3.9M18](/packages/mpociot-vat-calculator)[commerceguys/tax

Tax library with a flexible data model, predefined tax rates, powerful resolving logic.

286763.3k](/packages/commerceguys-tax)[omaralalwi/laravel-taxify

Laravel Taxify provides a set of helper functions and classes to simplify tax (VAT) calculations within Laravel applications. that allow developers to easily integrate tax calculation functionalities into their projects. it's offers a straightforward and efficient solution Designed to streamline the process of handling taxes.

471.7k](/packages/omaralalwi-laravel-taxify)[ibericode/vat-bundle

Bundle for using ibericode/vat in a Symfony environment

21254.5k](/packages/ibericode-vat-bundle)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
