Poland initially supported the mandatory quotas but now, with its new right-wing government, is against it.
It also held that the European Council, the body gathering the member states, "was not required to act unanimously when it adopted the contested decision". The government of Hungarian Prime Minister Viktor Orban has taken the stance that Hungary has the right to refuse entry to the primarily Muslim asylum seekers and refugees, claiming they threaten the country's cultural identity.
They also say that opening their borders to refugees from migrants from war-torn countries such as Syria could leave them open to the threat of terrorism.
The verdict by the court in Luxembourg was welcomed by the European Commission, the executive of the 28-nation bloc.
It is part of a scheme to relocate a total of 160,000 asylum seekers by September this year.
Commenting on the ruling, Germany Foreign Minister Sigmar Gabriel said it was a positive step that fully adhered to European values and law. We expect all European Union countries to respect and implement the ruling.
Sec. James Mattis: Reports Suggesting He Disagrees with Trump Are 'Ludicrous'
On Tuesday, North Korea provoked worldwide alarm after it fired a mid-range missile over the Japanese island of Hokkaido. Constant North Korean provocations do not seriously disturb Seoul-based foreigners like Matthew Crawford either.
In their case before the ECJ, Hungary and Slovakia argued that there had been procedural flaws and that the decision was neither a suitable response to the migrant crisis nor necessary to deal with it.
"Our position on quotas does not change", Prime Minister Robert Fico said.
"We will continue to work on having solidarity expressed in different ways other than forcing migrants [on Slovakia] from other countries that don't want to be here anyway".
Hungarian Foreign Minister Peter Szijjarto said the ruling was "outrageous and irresponsible", the Associated Press reports, and vowed Hungary would fight any attempts to resettle migrants there without government approval. "This decision jeopardizes the security and future of all of Europe".
"Today's ruling shows that no country can hide from their responsibilities to refugees", Iverna McGowan, Director of Amnesty's European Institutions Office, said in a statement.
'This decision practically and openly legitimates the power of the European Union above the member states'.
Under the plan, Hungary must admit more than 2,300 asylum seekers, while Slovakia must in the long term take in 1,400.